Package org.jscsi.parser

Examples of org.jscsi.parser.BasicHeaderSegment


    }

    @Override
    public void execute (ProtocolDataUnit pdu) throws IOException , InterruptedException , InternetSCSIException , DigestException , SettingsException {

        final BasicHeaderSegment bhs = pdu.getBasicHeaderSegment();
        final SCSICommandParser parser = (SCSICommandParser) bhs.getParser();

        ProtocolDataUnit responsePDU = null;// the response PDU

        // get command details in CDB
        final RequestSenseCdb cdb = new RequestSenseCdb(parser.getCDB());
        final FieldPointerSenseKeySpecificData[] illegalFieldPointers = cdb.getIllegalFieldPointers();

        if (illegalFieldPointers != null) {
            // an illegal request has been made

            SenseData senseData;

            if (cdb.getDescriptorFormat()) {
                // descriptor format sense data has been requested

                senseData = new DescriptorFormatSenseData(ErrorType.CURRENT,// errorType
                SenseKey.ILLEGAL_REQUEST,// sense key
                AdditionalSenseCodeAndQualifier.INVALID_FIELD_IN_CDB,// additional
                                                                     // sense
                                                                     // code
                                                                     // and
                                                                     // qualifier
                new SenseDataDescriptor[0]);// sense data descriptors

            } else {
                // fixed format sense data has been requested

                senseData = new FixedFormatSenseData(false,// valid
                ErrorType.CURRENT,// error type
                false,// file mark
                false,// end of medium
                false,// incorrect length indicator
                SenseKey.ILLEGAL_REQUEST,// sense key
                new FourByteInformation(),// information
                new FourByteInformation(),// command specific
                                          // information
                AdditionalSenseCodeAndQualifier.INVALID_FIELD_IN_CDB,// additional
                                                                     // sense
                                                                     // code
                                                                     // and
                                                                     // qualifier
                (byte) 0,// field replaceable unit code
                illegalFieldPointers[0],// sense key specific data, only
                                        // report first problem
                new AdditionalSenseBytes());// additional sense bytes
            }

            responsePDU = TargetPduFactory.createSCSIResponsePdu(false,// bidirectionalReadResidualOverflow
                    false,// bidirectionalReadResidualUnderflow
                    false,// residualOverflow
                    false,// residualUnderflow,
                    SCSIResponseParser.ServiceResponse.TARGET_FAILURE,// response,
                    SCSIStatus.CHECK_CONDITION,// status,
                    bhs.getInitiatorTaskTag(),// initiatorTaskTag,
                    0,// snackTag
                    0,// expectedDataSequenceNumber
                    0,// bidirectionalReadResidualCount
                    0,// residualCount
                    new ScsiResponseDataSegment(senseData, parser.getExpectedDataTransferLength()));// data
                                                                                                    // segment

        } else {
            /*
             * PDU is okay carry out command Sense data shall be available and cleared under the conditions defined in
             * SAM-3. If the device server has no other sense data available to return, it shall return the sense key
             * set to NO SENSE and the additional sense code set to NO ADDITIONAL SENSE INFORMATION. This will always be
             * the case with the jSCSI Target.
             */

            SenseData senseData;

            final SenseKey senseKey = SenseKey.NO_SENSE;
            final AdditionalSenseCodeAndQualifier additionalSense = AdditionalSenseCodeAndQualifier.NO_ADDITIONAL_SENSE_INFORMATION;

            if (cdb.getDescriptorFormat()) {
                // descriptor format sense data has been requested

                senseData = new DescriptorFormatSenseData(ErrorType.CURRENT,// errorType
                senseKey,// sense key
                additionalSense,// additional sense code and qualifier
                new SenseDataDescriptor[0]);// sense data descriptors

            } else {
                // fixed format sense data has been requested

                senseData = new FixedFormatSenseData(false,// valid
                ErrorType.CURRENT,// error type
                false,// file mark
                false,// end of medium
                false,// incorrect length indicator
                senseKey,// sense key
                new FourByteInformation(),// information
                new FourByteInformation(),// command specific
                                          // information
                additionalSense,// additional sense code and qualifier
                (byte) 0,// field replaceable unit code
                null,// sense key specific data, only report first
                     // problem
                null);// additional sense bytes
            }

            responsePDU = TargetPduFactory.createSCSIResponsePdu(false,// bidirectionalReadResidualOverflow
                    false,// bidirectionalReadResidualUnderflow
                    false,// residualOverflow
                    false,// residualUnderflow,
                    SCSIResponseParser.ServiceResponse.COMMAND_COMPLETED_AT_TARGET,// response,
                    SCSIStatus.GOOD,// status,
                    bhs.getInitiatorTaskTag(),// initiatorTaskTag,
                    0,// snackTag
                    0,// expectedDataSequenceNumber
                    0,// bidirectionalReadResidualCount
                    0,// residualCount
                    new ScsiResponseDataSegment(senseData, parser.getExpectedDataTransferLength()));// data
View Full Code Here


    }

    @Override
    public void execute (ProtocolDataUnit pdu) throws IOException , InterruptedException , InternetSCSIException , DigestException , SettingsException {

        final BasicHeaderSegment bhs = pdu.getBasicHeaderSegment();
        final TaskManagementFunctionRequestParser parser = (TaskManagementFunctionRequestParser) bhs.getParser();
        final int initiatorTaskTag = bhs.getInitiatorTaskTag();

        TaskManagementFunctionResponseParser.ResponseCode responseCode = ResponseCode.TASK_DOES_NOT_EXIST;

        switch (parser.getFunction()) {
            case ABORT_TASK :
View Full Code Here

    @Override
    public void execute (ProtocolDataUnit initialPdu) throws IOException , InterruptedException , InternetSCSIException , DigestException , SettingsException {

        // "receive" initial PDU
        BasicHeaderSegment bhs = initialPdu.getBasicHeaderSegment();
        initiatorTaskTag = bhs.getInitiatorTaskTag();

        boolean authenticated = false;

        do {// while initiator is not willing and not authorized to transit to
            // next stage

            // build text parameter string from current login PDU sequence
            final String requestTextParameters = receivePduSequence(initialPdu);

            // split key-value pairs
            final List<String> requestKeyValuePairs = TextParameter.tokenizeKeyValuePairs(requestTextParameters);

            // Vector for AuthMethod keys
            final List<String> authMethodKeyValuePairs = new Vector<String>();

            // log initiator's key-value pairs
            if (LOGGER.isDebugEnabled()) {
                final StringBuilder sb = new StringBuilder();
                sb.append("request key value pairs:\n");
                for (String s : requestKeyValuePairs)
                    sb.append("   " + s + "\n");
                LOGGER.debug(sb.toString());
            }

            // extract available AuthMethod key-value pair, so that settings can
            // finish
            // processing the other parameters before authorization begins
            String authMethodValues = null;
            if (!authenticated) {// authentication part one
                for (int i = 0; i < requestKeyValuePairs.size(); ++i) {
                    final String[] split = TextParameter.splitKeyValuePair(requestKeyValuePairs.get(i));
                    if (split == null) {
                        sendRejectPdu(LoginStatus.INITIATOR_ERROR);
                        throw new InternetSCSIException("key=value format error: " + requestKeyValuePairs.get(i));
                    }
                    if (TextKeyword.AUTH_METHOD.equals(split[0])) {
                        authMethodValues = split[1];
                        // remove key-value pair from Vector
                        requestKeyValuePairs.remove(i--);// correct for shifted
                                                         // indices
                        // no break here to catch all authMethodKeyValuePairs in
                        // else block
                    } else if (isAuthenticationKey(split[0])) {
                        // move key-value pair to authMethodKeyValuePairs
                        authMethodKeyValuePairs.add(requestKeyValuePairs.remove(i--));// correct for shifted
                                                                                      // indices
                    }
                }
                if (authMethodValues == null) {// missing AuthMethod key
                    sendRejectPdu(LoginStatus.MISSING_PARAMETER);// require
                                                                 // AuthMethod
                                                                 // to be
                                                                 // specified in
                                                                 // first PDU
                                                                 // sequence
                    // close connection
                    throw new InternetSCSIException("Missing AuthMethod key-value pair");
                }
            }

            // negotiate remaining parameters
            final Vector<String> responseKeyValuePairs = new Vector<String>();// these
                                                                              // will
                                                                              // be
                                                                              // sent
                                                                              // back
            if (!negotiator.negotiate(session.getTargetServer(), stageNumber, connection.isLeadingConnection(), ((TargetLoginPhase) targetPhase).getFirstPduAndSetToFalse(), requestKeyValuePairs, responseKeyValuePairs)) {
                // negotiation error
                sendRejectPdu(LoginStatus.INITIATOR_ERROR);
                throw new InternetSCSIException("negotiation failure");
            }

            // ** authentication ** (part two)
            if (!authenticated) {
                if (authMethodValues.contains(TextKeyword.NONE)) {

                    authenticated = true;
                    responseKeyValuePairs.add(TextParameter.toKeyValuePair(TextKeyword.AUTH_METHOD,// key
                            TextKeyword.NONE));// value

                    // concatenate key value pairs to single string
                    final String responseString = TextParameter.concatenateKeyValuePairs(responseKeyValuePairs);

                    if (LOGGER.isDebugEnabled()) LOGGER.debug("response: " + responseString);

                    // send reply (sequence), set transit bit of last PDU
                    sendPduSequence(responseString, requestedNextStageNumber);

                    // leave this (and proceed to next) stage
                    if (requestedNextStageNumber == LoginStage.LOGIN_OPERATIONAL_NEGOTIATION || requestedNextStageNumber == LoginStage.FULL_FEATURE_PHASE) {
                        nextStageNumber = requestedNextStageNumber;
                        return;
                    }
                } else {
                    // TODO support CHAP (and use String
                    // authMethodKeyValuePairs)
                    LOGGER.error("initiator attempted CHAP authentication");
                    // nextStageNumber = null;//no change
                    return;
                }

            }

        } while (!bhs.isFinalFlag() && !authenticated);
    }
View Full Code Here

     *
     * @param pdu the PDU to check
     * @return <code>true</code> if the PDU checks out
     */
    protected boolean checkPdu (ProtocolDataUnit pdu) {
        final BasicHeaderSegment bhs = pdu.getBasicHeaderSegment();
        final LoginRequestParser parser = (LoginRequestParser) bhs.getParser();
        if (bhs.getOpCode() == OperationCode.LOGIN_REQUEST && parser.getCurrentStageNumber() == stageNumber && bhs.getInitiatorTaskTag() == initiatorTaskTag) return true;
        return false;
    }
View Full Code Here

        // StringBuilder for the key-value pairs received during this sequence
        final StringBuilder stringBuilder = new StringBuilder();

        // for accessing the fields of the last received PDU
        BasicHeaderSegment bhs;
        LoginRequestParser parser;

        // begin sequence
        int sequenceLength = 1;
        while (sequenceLength <= session.getTargetServer().getConfig().getInMaxRecvTextPduSequenceLength()) {
            bhs = pdu.getBasicHeaderSegment();
            parser = (LoginRequestParser) bhs.getParser();

            // check PDU
            if (!checkPdu(pdu)) {
                // send login reject and leave stage
                sendRejectPdu(LoginStatus.INVALID_DURING_LOGIN);
View Full Code Here

     */
    protected final void sendPduSequence (final String keyValuePairs, final LoginStage nextStage) throws SettingsException , InterruptedException , IOException , InternetSCSIException , DigestException {

        // some variables
        ProtocolDataUnit pdu;
        BasicHeaderSegment bhs;
        LoginRequestParser parser;
        boolean continueFlag = true;
        boolean transitFlag = false;

        // split input string into text data segments
        final ByteBuffer[] dataSegments = ReadWrite.stringToTextDataSegments(keyValuePairs,// string
                settings.getMaxRecvDataSegmentLength());// bufferSize

        // send all data segments (and receive confirmations)
        for (int i = 0; i < dataSegments.length; ++i) {

            // adjust flags
            if (i == dataSegments.length - 1) {
                continueFlag = false;
                if (stageNumber != nextStage) transitFlag = true;
            }

            // create and send PDU
            pdu = TargetPduFactory.createLoginResponsePdu(transitFlag,// transitFlag
                    continueFlag,// continueFlag
                    stageNumber,// currentStage
                    nextStage,// nextStage
                    session.getInitiatorSessionID(),// initiatorSessionID
                    session.getTargetSessionIdentifyingHandle(),// targetSessionIdentifyingHandle
                    initiatorTaskTag, LoginStatus.SUCCESS,// status
                    dataSegments[i]);// dataSegment
            connection.sendPdu(pdu);

            // receive confirmation
            if (continueFlag) {
                // receive and check
                pdu = connection.receivePdu();
                bhs = pdu.getBasicHeaderSegment();
                parser = (LoginRequestParser) bhs.getParser();
                if (!checkPdu(pdu) || parser.isContinueFlag()) {
                    // send login reject and leave stage
                    sendRejectPdu(LoginStatus.INITIATOR_ERROR);
                    throw new InternetSCSIException();
                }
View Full Code Here

    @Override
    public void execute (ProtocolDataUnit pdu) throws IOException , InterruptedException , InternetSCSIException , DigestException , IllegalArgumentException , SettingsException {
        LOGGER.debug("Entering LOPN Stage");

        BasicHeaderSegment bhs = pdu.getBasicHeaderSegment();
        initiatorTaskTag = bhs.getInitiatorTaskTag();

        String keyValuePairProposal = receivePduSequence(pdu);

        // negotiate parameters, leave if unsuccessful
        final List<String> requestKeyValuePairs = TextParameter.tokenizeKeyValuePairs(keyValuePairProposal);
View Full Code Here

        }

        if (LOGGER.isDebugEnabled()) LOGGER.debug("Receiving this PDU:\n" + pdu);

        // parse sequence counters
        final BasicHeaderSegment bhs = pdu.getBasicHeaderSegment();
        final InitiatorMessageParser parser = (InitiatorMessageParser) bhs.getParser();
        // final int commandSequenceNumber = parser.getCommandSequenceNumber();
        // final int expectedStatusSequenceNumber = parser.getExpectedStatusSequenceNumber();

        if (LOGGER.isDebugEnabled()) {
            // sharrajesh
            // Needed to debug, out of order receiving of StatusSN and ExpStatSN
            if (bhs.getOpCode() == OperationCode.SCSI_COMMAND) {
                final SCSICommandParser scsiParser = (SCSICommandParser) bhs.getParser();
                ScsiOperationCode scsiOpCode = ScsiOperationCode.valueOf(scsiParser.getCDB().get(0));
                LOGGER.debug("scsiOpCode = " + scsiOpCode);
                LOGGER.debug("CDB bytes: \n" + Debug.byteBufferToString(scsiParser.getCDB()));
            }
            // LOGGER.debug("parser.expectedStatusSequenceNumber: " + expectedStatusSequenceNumber);
View Full Code Here

    private static final ProtocolDataUnitFactory factory = new ProtocolDataUnitFactory();

    public static final ProtocolDataUnit createDataInPdu (boolean finalFlag, boolean acknowledgeFlag, boolean residualOverflowFlag, boolean residualUnderflowFlag, boolean statusFlag, SCSIStatus status, long logicalUnitNumber, int initiatorTaskTag, int targetTransferTag, int dataSequenceNumber,//
            int bufferOffset, int residualCount, ByteBuffer dataSegment) {
        final ProtocolDataUnit pdu = factory.create(false, finalFlag, OperationCode.SCSI_DATA_IN, "None", "None");
        final BasicHeaderSegment bhs = pdu.getBasicHeaderSegment();
        final DataInParser parser = (DataInParser) bhs.getParser();
        parser.setAcknowledgeFlag(acknowledgeFlag);
        parser.setResidualOverflowFlag(residualOverflowFlag);
        parser.setResidualUnderflowFlag(residualUnderflowFlag);
        parser.setStatusFlag(statusFlag);
        parser.setStatus(status);
        parser.setLogicalUnitNumber(logicalUnitNumber);
        bhs.setInitiatorTaskTag(initiatorTaskTag);
        parser.setTargetTransferTag(targetTransferTag);
        parser.setDataSequenceNumber(dataSequenceNumber);
        parser.setBufferOffset(bufferOffset);
        parser.setResidualCount(residualCount);
        pdu.setDataSegment(dataSegment);
View Full Code Here

        return pdu;
    }

    public static final ProtocolDataUnit createLoginResponsePdu (boolean transitFlag, boolean continueFlag, LoginStage currentStage, LoginStage nextStage, ISID initiatorSessionID, short targetSessionIdentifyingHandle, int initiatorTaskTag, LoginStatus status, ByteBuffer dataSegment) {
        final ProtocolDataUnit pdu = factory.create(false, transitFlag, OperationCode.LOGIN_RESPONSE, "None", "None");
        final BasicHeaderSegment bhs = pdu.getBasicHeaderSegment();
        final LoginResponseParser parser = (LoginResponseParser) bhs.getParser();
        parser.setContinueFlag(continueFlag);
        parser.setCurrentStageNumber(currentStage);
        parser.setNextStageNumber(nextStage);
        parser.setInitiatorSessionID(initiatorSessionID);
        parser.setTargetSessionIdentifyingHandle(targetSessionIdentifyingHandle);
        bhs.setInitiatorTaskTag(initiatorTaskTag);
        parser.setStatus(status);
        pdu.setDataSegment(dataSegment);
        return pdu;
    }
View Full Code Here

TOP

Related Classes of org.jscsi.parser.BasicHeaderSegment

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.