Search in sources :

Example 1 with PacketType

use of dev.hawala.xns.level1.IDP.PacketType in project dodo by devhawala.

the class GetXNSPackets method main.

/**
 * Main startup method
 *
 * @param args
 *          ignored
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    // Will be filled with NICs
    List<PcapIf> alldevs = new ArrayList<PcapIf>();
    // For any error msgs
    StringBuilder errbuf = new StringBuilder();
    /**
     *************************************************************************
     * First get a list of devices on this system
     *************************************************************************
     */
    int r = Pcap.findAllDevs(alldevs, errbuf);
    if (r == Pcap.NOT_OK || alldevs.isEmpty()) {
        System.err.printf("Can't read list of devices, error is %s", errbuf.toString());
        return;
    }
    System.err.printf("r -> %d\n", r);
    System.err.printf("alldevs.size() = %d\n", alldevs.size());
    System.out.println("Network devices found:");
    PcapIf matchedDev = null;
    int i = 0;
    for (PcapIf device : alldevs) {
        String description = (device.getDescription() != null) ? device.getDescription() : "No description available";
        if ("tap0".equals(description)) {
            System.err.println("** found tap0 by description");
            matchedDev = device;
        }
        if ("tap0".equals(device.getName())) {
            System.err.println("** found tap0 by name");
            matchedDev = device;
        }
        byte[] addr = device.getHardwareAddress();
        String addrLen = "X";
        String sep = "";
        String mac = "";
        if (addr != null) {
            addrLen = "" + addr.length;
            for (byte b : addr) {
                mac = String.format("%s%s%02X", mac, sep, b);
                sep = "-";
            }
        }
        System.out.printf("#%d: %s (%s)[%s] [%s]\n", i++, device.getName(), addrLen, mac, description);
    }
    // We know we have at least 1 device
    PcapIf device = (matchedDev != null) ? matchedDev : alldevs.get(alldevs.size() - 1);
    System.out.printf("\nChoosing '%s' on your behalf:\n", (device.getDescription() != null) ? device.getDescription() : device.getName());
    /**
     *************************************************************************
     * Second we open up the selected device
     *************************************************************************
     */
    // Capture all packets, no trucation
    int snaplen = 64 * 1024;
    // capture all packets
    int flags = Pcap.MODE_PROMISCUOUS;
    // 10 * 1000;           // 10 seconds in millis
    int timeout = 1;
    Pcap pcap = Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf);
    if (pcap == null) {
        System.err.printf("Error while opening device for capture: " + errbuf.toString());
        return;
    }
    /**
     *************************************************************************
     * Third we create a packet handler which will receive packets from the
     * libpcap loop.
     *************************************************************************
     */
    PcapPacketHandler<String> jpacketHandler = new PcapPacketHandler<String>() {

        public void nextPacket(PcapPacket packet, String user) {
            if (packet.getByte(12) != (byte) 0x06 || packet.getByte(13) != (byte) 0x00) {
                // System.out.println("packet skipped...");
                return;
            }
            System.out.printf("\n\nReceived packet at %s caplen=%-4d len=%-4d %s\n", new Date(packet.getCaptureHeader().timestampInMillis()), // Length actually captured
            packet.getCaptureHeader().caplen(), // Original length
            packet.getCaptureHeader().wirelen(), // User supplied object
            user);
            // System.out.println(packet);
            int payloadStart = 14;
            int payloadLength = packet.getCaptureHeader().caplen() - payloadStart;
            NetPacket np = new NetPacket(packet.getByteArray(payloadStart, payloadLength));
            IDP idp = new IDP(np);
            PacketType packetType = idp.getPacketType();
            if (packetType == PacketType.SPP) {
                SPP spp = new SPP(idp);
                System.out.printf("%s\n", spp.toString());
                System.out.printf("payload: %s\n", spp.payloadToString());
            } else if (packetType == PacketType.ERROR) {
                Error err = new Error(idp);
                System.out.printf("%s\n", err.toString());
                System.out.printf("payload: %s\n", err.payloadToString());
            } else if (packetType == PacketType.PEX) {
                PEX pex = new PEX(idp);
                System.out.printf("%s\n", pex.toString());
                System.out.printf("payload: %s\n", pex.payloadToString());
            } else {
                System.out.printf("%s\n", np.toString());
                System.out.printf("payload: %s\n", np.payloadToString());
            }
        }
    };
    // JBufferHandler<String> jbufferHandler = new JBufferHandler<String>() {
    // 
    // @Override
    // public void nextPacket(PcapHeader header, JBuffer buffer, String userDate) {
    // buffer.
    // }
    // 
    // }
    /**
     *************************************************************************
     * Fourth we enter the loop and tell it to capture 10 packets. The loop
     * method does a mapping of pcap.datalink() DLT value to JProtocol ID, which
     * is needed by JScanner. The scanner scans the packet buffer and decodes
     * the headers. The mapping is done automatically, although a variation on
     * the loop method exists that allows the programmer to sepecify exactly
     * which protocol ID to use as the data link type for this pcap interface.
     *************************************************************************
     */
    pcap.loop(100000, jpacketHandler, "jNetPcap rocks!");
    /**
     *************************************************************************
     * Last thing to do is close the pcap handle
     *************************************************************************
     */
    pcap.close();
    System.out.printf("GetXNSPackets done\n");
}
Also used : PEX(dev.hawala.xns.level2.PEX) Pcap(org.jnetpcap.Pcap) ArrayList(java.util.ArrayList) NetPacket(dev.hawala.xns.level0.NetPacket) Error(dev.hawala.xns.level2.Error) Date(java.util.Date) SPP(dev.hawala.xns.level2.SPP) IDP(dev.hawala.xns.level1.IDP) PcapPacket(org.jnetpcap.packet.PcapPacket) PacketType(dev.hawala.xns.level1.IDP.PacketType) PcapPacketHandler(org.jnetpcap.packet.PcapPacketHandler) PcapIf(org.jnetpcap.PcapIf)

Example 2 with PacketType

use of dev.hawala.xns.level1.IDP.PacketType in project dodo by devhawala.

the class Tests method main.

public static void main(String[] args) {
    int[] rawData = { // checksum
    0x17, // checksum
    0x59, // length = 40
    0x00, // length = 40
    0x28, // transportControl
    0x00, // packetType
    0x04, // dst network number
    0x00, // dst network number
    0x00, // dst network number
    0x00, // dst network number
    0x00, // dst address
    0xff, // dst address
    0xff, // dst address
    0xff, // dst address
    0xff, // dst address
    0xff, // dst address
    0xff, // dst socket
    0x00, // dst socket
    0x30, // src network number
    0x00, // src network number
    0x00, // src network number
    0x00, // src network number
    0x00, // src address
    0x08, // src address
    0x00, // src address
    0x27, // src address
    0xd2, // src address
    0x97, // src address
    0x6e, // src socket
    0x00, // src socket
    0x30, // IDP payload
    0x91, 0x35, 0x05, 0x99, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    byte[] rawPayload = new byte[rawData.length];
    for (int i = 0; i < rawData.length; i++) {
        rawPayload[i] = (byte) (0xFF & rawData[i]);
    }
    NetPacket netPacket = new NetPacket(rawPayload);
    IDP idpPacket = new IDP(netPacket);
    switch(idpPacket.getPacketType()) {
        case PEX:
            PEX pexPacket = new PEX(idpPacket);
            System.out.printf(pexPacket.toString());
            System.out.printf("\npayload %s\n", pexPacket.payloadToString());
            System.out.printf("\nraw packet payload %s\n", pexPacket.idp.packet.payloadToString());
            // pexPacket.idp.computeChecksum_A();
            // System.out.printf("=> recomputed checksum_A: 0x%04X\n", pexPacket.idp.getChecksum());
            // pexPacket.idp.computeChecksum_B();
            // System.out.printf("=> recomputed checksum_B: 0x%04X\n", pexPacket.idp.getChecksum());
            // pexPacket.idp.computeChecksum_C();
            // System.out.printf("=> recomputed checksum_C: 0x%04X\n", pexPacket.idp.getChecksum());
            // pexPacket.idp.computeChecksum_D();
            // System.out.printf("=> recomputed checksum_D: 0x%04X\n", pexPacket.idp.getChecksum());
            pexPacket.idp.updateChecksum();
            System.out.printf("=> recomputed checksum: 0x%04X\n", pexPacket.idp.getChecksum());
            PEX response = new PEX(NETWORK_NUMBER_BYTES);
            response.idp.asReplyTo(pexPacket.idp);
            response.idp.setDstNetwork(NETWORK_NUMBER);
            response.idp.setSrcNetwork(NETWORK_NUMBER);
            response.idp.setSrcHost(HOST_ADDRESS);
            response.setIdentification(pexPacket.getIdentification());
            response.setClientType(pexPacket.getClientType());
            System.out.printf("\n=> response packet:\n");
            System.out.printf(response.toString());
            System.out.printf("\npayload %s\n", response.payloadToString());
            System.out.printf("\nraw packet payload %s\n", response.idp.packet.payloadToString());
            Payload checkPayload = new WorkPayload(response.idp.getLength());
            checkPayload.copy(response.idp.packet);
            System.out.printf("\n     check payload %s\n", checkPayload.payloadToString());
            break;
        default:
            System.out.printf(idpPacket.toString());
            System.out.printf("\npayload %s", idpPacket.payloadToString());
            break;
    }
    System.out.println();
}
Also used : PEX(dev.hawala.xns.level2.PEX) IDP(dev.hawala.xns.level1.IDP) NetPacket(dev.hawala.xns.level0.NetPacket) Payload(dev.hawala.xns.level0.Payload)

Example 3 with PacketType

use of dev.hawala.xns.level1.IDP.PacketType in project dodo by devhawala.

the class BootResponder method accept.

@Override
public void accept(IDP rcvIdp) {
    // service currently stopped...
    if (this.sender == null) {
        return;
    }
    PacketType packetType = rcvIdp.getPacketType();
    if (packetType == PacketType.BOOT_SERVER_PACKET) {
        this.logf("boot-server-packet %s\ndata: 0x %04X %04X %04X %04X %04X %04X\n", rcvIdp.toString(), rcvIdp.rdCardinal(0), rcvIdp.rdCardinal(2), rcvIdp.rdCardinal(4), rcvIdp.rdCardinal(6), rcvIdp.rdCardinal(8), rcvIdp.rdCardinal(10));
        int reqType = rcvIdp.rdCardinal(0);
        if (reqType == 1) {
            // simpleRequest
            // get request data
            long bfn0 = rcvIdp.rdCardinal(2);
            long bfn1 = rcvIdp.rdCardinal(4);
            long bfn2 = rcvIdp.rdCardinal(6);
            long bfn = (bfn0 << 32) | (bfn1 << 16) | bfn2;
            this.logf("## bootSvc: processing simple-request from 0x%012X for boot-file-number 0x%012X\n", rcvIdp.getSrcHost(), bfn);
            // start new download session
            if (!this.bootFiles.containsKey(bfn)) {
                this.logf("## bootSvc : ERROR -> no bootfile defined for boot-file-number 0x%012X\n", bfn);
                return;
            }
            File bootfile = this.bootFiles.get(bfn);
            this.logf("## bootSvc: sending file '%s' via simpleFile for boot-file-number 0x%012X\n", bootfile.getName(), bfn);
            // prepare idp packet for sending the boot file
            IDP idp = new IDP().asReplyTo(rcvIdp).withSource(this.localEndpoint);
            // simpleData (response to simpleRequest)
            idp.wrCardinal(0, 2);
            idp.wrCardinal(2, (int) bfn0);
            idp.wrCardinal(4, (int) bfn1);
            idp.wrCardinal(6, (int) bfn2);
            // start sending thread
            try {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(bootfile));
                Thread thr = new Thread(new SimpleDataSender(bis, idp, this.sender, this.verbose));
                thr.setDaemon(true);
                thr.start();
            } catch (FileNotFoundException e) {
                this.logf("## bootSvc : ERROR -> failed to access bootfile boot-file-number 0x%012X: %s\n", bfn, e.getMessage());
                return;
            }
        } else if (reqType == 3) {
            // sppRequest
            // get request data
            long bfn0 = rcvIdp.rdCardinal(2);
            long bfn1 = rcvIdp.rdCardinal(4);
            long bfn2 = rcvIdp.rdCardinal(6);
            long bfn = (bfn0 << 32) | (bfn1 << 16) | bfn2;
            int otherConnectionID = rcvIdp.rdCardinal(8);
            this.logf("## bootSvc: processing SPP-request from 0x%012X connID 0x%04X for boot-file-number 0x%012X\n", rcvIdp.getSrcHost(), otherConnectionID, bfn);
            // start new download session
            if (!this.bootFiles.containsKey(bfn)) {
                this.logf("## bootSvc : ERROR -> no bootfile defined for boot-file-number 0x%012X\n", bfn);
                return;
            }
            int myConnectionID = (this.lastConnId + 3) & 0xFFFF;
            this.lastConnId = myConnectionID;
            try {
                File bootfile = this.bootFiles.get(bfn);
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(bootfile));
                int key = (otherConnectionID << 16) | myConnectionID;
                Request request = new Request(bis);
                this.requests.put(key, request);
                this.logf("## bootSvc: created session key 0x%08X for request, providing boot file '%s'\n", key, bootfile.getName());
                // send SPP "connection opened" packet response
                // with request to acknowledge for triggering the send mechanism
                SPP spp = new SPP();
                spp.idp.asReplyTo(rcvIdp).withSource(this.localEndpoint);
                spp.asSystemPacket().setDstConnectionId(otherConnectionID).setSrcConnectionId(myConnectionID).setSequenceNumber(0).setAllocationNumber(0).setAcknowledgeNumber(0).setDatastreamType(SST_DATA);
                this.dumpSpp("## bootSvc - 1st reply SPP (connection open reply):", spp);
                this.sender.send(spp.idp);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                }
                // send the next reply packet *with* data, assuming the requestor now considers the connection already opened
                SPP dataSpp = new SPP();
                dataSpp.idp.asReplyTo(rcvIdp);
                request.fillNextPacket(dataSpp);
                dataSpp.setDstConnectionId(otherConnectionID).setSrcConnectionId(myConnectionID).setAllocationNumber(0).setAcknowledgeNumber(0).asSendAcknowledge().setDatastreamType(SST_DATA).setSequenceNumber(0);
                this.dumpSpp("## bootSvc - reply SPP:", dataSpp);
                this.sender.send(dataSpp.idp);
                this.logf("## bootSvc - sent 2nd SPP reply as data packet (skipped connect handskake)\n");
            } catch (FileNotFoundException e) {
                this.logf("## bootSvc : ERROR -> failed to access bootfile boot-file-number 0x%012X: %s\n", bfn, e.getMessage());
                return;
            }
        // // send SPP "connection opened" packet response
        // // with request to acknowledge for triggering the send mechanism
        // SPP spp = new SPP();
        // spp.idp.asReplyTo(rcvIdp).withSource(this.localEndpoint);
        // spp.asSystemPacket()
        // .asSendAcknowledge()
        // .setDstConnectionId(otherConnectionID)
        // .setSrcConnectionId(myConnectionID)
        // .setSequenceNumber(0)
        // .setAllocationNumber(0)
        // .setAcknowledgeNumber(0)
        // .setDatastreamType(SST_DATA);
        // this.dumpSpp("## bootSvc - reply SPP:", spp);
        // this.sender.send(spp.idp);
        } else {
            this.logf("## bootSvc: unsupported request type %d, ignoring request\n", reqType);
        }
    } else if (packetType == PacketType.SPP) {
        // packet in a SPP-flavor boot file transfer: check the session
        SPP rcvSpp = new SPP(rcvIdp);
        this.dumpSpp("## bootSvc - ingone SPP:", rcvSpp);
        int key = (rcvSpp.getSrcConnectionId() << 16) | rcvSpp.getDstConnectionId();
        Request request = this.requests.get(key);
        this.logf("## bootSvc: resulting session key 0x%08X -> request found: %s\n", key, Boolean.toString(request != null));
        if (request == null) {
            // no session => no response possible
            return;
        }
        // check state in the packet ping-pong
        int sst = rcvSpp.getDatastreamType() & 0xFF;
        if (sst == SST_DATA) {
            // ongoing transfer: prepare response packet common fields
            SPP rplySpp = new SPP();
            rplySpp.idp.asReplyTo(rcvIdp);
            rplySpp.setDstConnectionId(rcvSpp.getSrcConnectionId()).setSrcConnectionId(rcvSpp.getDstConnectionId()).setAllocationNumber(0).setAcknowledgeNumber(0).setDatastreamType((byte) SppConnection.SST_CLOSE_CONFIRM);
            // check which page to send this time
            int nextPageNo = request.nextPageToSend();
            this.logf("## bootSvc: next bootfile page = %d\n", nextPageNo);
            int ackNo = rcvSpp.getAcknowledgeNumber();
            if (ackNo == nextPageNo) {
                // last page sent was acknowledged, so send next page
                this.logln("## bootSvc: request.fillNextPacket(rplySpp)");
                if (request.fillNextPacket(rplySpp)) {
                    rplySpp.asSendAcknowledge().setDatastreamType(SST_DATA).setSequenceNumber(nextPageNo);
                } else {
                    // the boot file is complete, so signal this to booting machine
                    this.logln("## bootSvc: ... reached end-of-bootfile");
                    rplySpp.setDatastreamType((byte) SppConnection.SST_CLOSE_REQUEST).setSequenceNumber(nextPageNo);
                }
            } else {
                // last page sent is not acknowledged, so resend it
                this.logln("## bootSvc: request.resendLastPacket(rplySpp)");
                request.resendLastPacket(rplySpp);
                rplySpp.asSendAcknowledge().setDatastreamType(SST_DATA).setSequenceNumber(nextPageNo - 1);
            }
            // finally send the packet
            this.sendIDP(rplySpp);
        } else if (sst == SppConnection.SST_CLOSE_REQUEST || sst == SppConnection.SST_CLOSE_CONFIRM) {
            // this is either:
            // -> a request from the booting machine to close: reply with close confirmation
            // or
            // -> the response to our close request: we have to reply with (also) a confirmation
            SPP rplySpp = new SPP();
            rplySpp.idp.asReplyTo(rcvIdp).withSource(this.localEndpoint);
            rplySpp.setDstConnectionId(rcvSpp.getSrcConnectionId()).setSrcConnectionId(rcvSpp.getDstConnectionId()).setSequenceNumber(rcvSpp.getAcknowledgeNumber()).setAllocationNumber(0).setAcknowledgeNumber(0).setDatastreamType((byte) SppConnection.SST_CLOSE_CONFIRM);
            this.sendIDP(rplySpp);
            // if drop request => this will silently ignore the SST_CLOSE_CONFIRM reply to our confirmation packet
            request.close();
            this.requests.remove(key);
            this.logf("## bootSvc: closed session 0x%08X\n", key);
        }
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) FileInputStream(java.io.FileInputStream) SPP(dev.hawala.xns.level2.SPP) IDP(dev.hawala.xns.level1.IDP) BufferedInputStream(java.io.BufferedInputStream) PacketType(dev.hawala.xns.level1.IDP.PacketType) File(java.io.File)

Aggregations

IDP (dev.hawala.xns.level1.IDP)3 NetPacket (dev.hawala.xns.level0.NetPacket)2 PacketType (dev.hawala.xns.level1.IDP.PacketType)2 PEX (dev.hawala.xns.level2.PEX)2 SPP (dev.hawala.xns.level2.SPP)2 Payload (dev.hawala.xns.level0.Payload)1 Error (dev.hawala.xns.level2.Error)1 BufferedInputStream (java.io.BufferedInputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 Pcap (org.jnetpcap.Pcap)1 PcapIf (org.jnetpcap.PcapIf)1 PcapPacket (org.jnetpcap.packet.PcapPacket)1 PcapPacketHandler (org.jnetpcap.packet.PcapPacketHandler)1