Code Monkey home page Code Monkey logo

java-coap's Introduction

mbed CoAP

CircleCI License codecov Known Vulnerabilities

Maintenance

This repository is under minimal maintenance. There is a more actively developed version available at https://github.com/open-coap/java-coap - you might want to check that repository out. There are API differences, though.

Introduction

This library makes it easy to integrate a Java SE enabled device with CoAP based services like Izuma Networks Device Management. It can also help to emulate an embedded device for prototyping and testing purposes.

The following features are supported by the library:

  • Complete CoAP support
    • The Constrained Application Protocol RFC 7252
    • Observing Resources in the Constrained Application Protocol RFC 7641
    • Block-Wise Transfers in the Constrained Application Protocol RFC 7959
  • CoRE Link Format processing API
    • Constrained RESTful Environments (CoRE) Link Format RFC 6690
  • CoAP server mode
  • CoAP client mode
  • Coap over tcp, tls RFC 8323
    • excluding: websockets, observations with BERT blocks
  • Network transports:
    • UDP (plain text)
    • TCP (plain text)
    • TLS
  • LwM2M TLV and JSON data formats

Requirements

Runtime:

  • JRE 8
  • JRE 11

Development:

  • JDK 8
  • maven 3.x

Using the Library

Add repository to build file:

<repositories>
	<repository>
	    <id>jitpack.io</id>
	    <url>https://jitpack.io</url>
	</repository>
</repositories>

Add dependency into your pom.xml:

<dependency>
    <groupId>com.mbed.java-coap</groupId>
    <artifactId>coap-core</artifactId>
    <version>{VERSION}</version>
</dependency>

Creating a Server

Initializing, starting and stopping the server

To initialize a server, you must at minimum define the port number. You must set the server parameters before starting a server.

CoapServer server = CoapServer.builder().transport(5683).build();
server.start();

To stop a server, use the stop() method.

server.stop();

Adding request handlers

You can add handlers before or while the server is running. There can be several URI paths assigned to the same handler. You can also remove a handler at any time.

CoapHandler handler = new ReadOnlyCoapResource("24");
server.addRequestHandler("/temperature", handler);

server.removeRequestHandler(handler);

Creating CoAP resources

To create a CoAP resource, you must implement a CoapHandler. There is one abstract helper class CoapResource that can be extended. At minimum, implement the get() method.

The following example overrides get() and put() and creates a simple CoAP resource:

public class SimpleCoapResource extends CoapResource {
    private String body="Hello World";
    
    @Override
    public void get(CoapExchange ex) throws CoapCodeException {
        ex.setResponseBody("Hello World");
        ex.setResponseCode(Code.C205_CONTENT);
        ex.sendResponse();
    }
    
    @Override
    public void put(CoapExchange ex) throws CoapCodeException {
      body = ex.getRequestBodyString();        
        ex.setResponseCode(Code.C204_CHANGED);
        ex.sendResponse();
    }
}

Creating a client

To make a CoAP request, use the class CoapClient. It uses fluent API. The following is a simple example on the usage:

CoapClient client = CoapClientBuilder.newBuilder(new InetSocketAddress("localhost",5683)).build();

CoapPacket coapResp = client.resource("/s/temp").sync().get();

coapResp = client.resource("/a/relay").payload("1", MediaTypes.CT_TEXT_PLAIN).sync().put();
    
//it is important to close connection in order to release socket
client.close();

Example client

This example client demonstrates how to build coap client.

Development

Issues with localhost on Ubuntu

Ubuntu has IP addresses for localhost, 127.0.0.1 and 127.0.1.1. This causes problems with CoAP packets, the request and response address does not match. Change both addresses to 127.0.0.1 or comment or remove the latter from /etc/hosts and change hostname to localhost.

To check hostname:

    hostname

To change hostname to localhost:

    sudo hostname localhost

Build

mvn clean install

Build with all checks enabled

mvn clean install -P ci

Update license header

mvn com.mycila:license-maven-plugin:format

Contributions

All contributions are Apache 2.0. Only submit contributions where you have authored all of the code. If you do this on work time make sure your employer is OK with this.

License

Unless specifically indicated otherwise in a file, files are licensed under the Apache 2.0 license, as can be found in: LICENSE

java-coap's People

Contributors

dependabot[bot] avatar irinil avatar jannekiiskila avatar kallevayrynen avatar norbert-david avatar olli-miettinen-arm avatar samhaa01 avatar smolboarm avatar snyk-bot avatar szysas avatar toikarin-arm avatar wipu-arm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java-coap's Issues

Jar on jitpack.io appears to be missing classes

When I download the 5.0.0 coap-core jar from jitpack.io it appears like the TransportExecutors class is missing so the example client does not compile.

I'm downloading via gradle, and I can confirm that the jar is downloaded and contains most of the coap-core classes, but TransportExecutors in com.mbed.coap.transport is not there.

I'm using CoapCli as a sample to try out the API but it does not compile with this class.

I want to use TLS which is new to 5.0.0 so using an older version is not an option.

I'm investigating building a copy for my own use, but I assume that if there is an issue with the jar on jitpack it would be better overall to have a complete jar available.

Thanks.

[Potential] Security Vulnerabilities within java-coap

Hello developers of java-coap,

My name is Bruno, and I'm an MSc. student in Brazil within the Institute of Computing from the University of Campinas.
As part of my research on the application of fuzzing techniques for robustness and security black-box testing of CoAP implementations, I've tested your library. The sample used in my research was compiled from distribution/commit 23e62f3 @ 2018-03-21. The application used to test it was bsmelo@52a9b80.

I'm contacting you because the application mentioned above was one of the samples for which our tool was able to detect robustness and/or security issues. In a broad sense, every failure we found can actually be classified as a security vulnerability, because they impact availability --- the application either aborts or needs forceful restart in order to restore servicing CoAP requests. However, we didn't go as far as performing a thorough root-cause analysis for those failures, since it would be unfeasible for us (more than 100 failures were detected across 25 samples, each one using a different CoAP library, spanning 8 programming languages) and thus out-of-scope of this particular research.

We think that one of our main contributions is the opportunity to make a real-world impact on IoT security by reporting those failures to CoAP libraries' maintainers, with a comprehensible and easy way to replicate them so developers can further investigate and fix those failures. So, in order to follow up with a responsible disclosure process, we ask for a proper e-mail address (or any other form of contact) so we can send you:

  • A script to reproduce the failures;
  • A pcap file used by the script, containing the packets causing the failures;
  • A logfile with the stacktraces we got for each reported failure.

We expect a reply anytime soon.
Please let us know if which form of contact should we use --- or if it's ok to use this channel.

Thanks & Regards,
Bruno Melo.

Adding the library

Hello, I'm interested in the library but I couldn't add it to my android studio. Can you help please!

Difference with californium project ?

Hi guys,
I just discover your project and It seems pretty similar to Californium project, I mean this is a Java SE implementation of CoAP.
So my naïve question is : what are the differences ? why creating another java project ?
Thx 🙏

Is this project active ?

Hi,

Some questions :

I would like to know if this project is still actively maintain ?

@szysas I also discover there was a project to integrate CoAP in OpenJDK named Kona. I saw that you contribute code to this project but I understand the kona project is not active anymore, correct ? Could you share a bit what happens ?

Some context :

I'm the main maintainer of Leshan project (LWM2M implementation for java).
Leshan is mainly based on Californium for coap.
Recently I try to abstract the transport layer of Leshan to be able to add new implementation based on different protocol (e.g. mqtt) or different CoAP library.
We currently search what protocol/library we should use to test this abstraction. (eclipse-leshan/leshan#1338)

Bound to other IP-Addresses

Hello,

I created a new method for the server. With this method you can bind other ip addresses in the same network and not only with localhost.

public CoapServerBuilderForUdp transport(InetAddress address,int port) { transport(new DatagramSocketTransport(new InetSocketAddress(address,port))); return this; }

If you find it useful I can make a pull request. If this feature exists already (for example with the CoapTransport) and you think is not necessary please let me know!

Thank you for your time!

Service hangs?

Sorry for the very vague report here, but we are seeing some weird occurrences in our service. We use your library for COAP exchanges. The library runs perfectly when we start our service and we have successful packet exchange and everything. It runs smoothly for quite a few hours, but then something undetected happens.

Logs don't indicate any traffic
tcpdump confirms there is traffic coming in
netstat confirms the service is still listening to the udp port

Restarting the container hosting the service fixes the problem.

Any suggestions or ideas to where I should start looking? and is there anything I can provide to make debugging possible?

How is it possible to send messages from server to client?

Hi

I was looking into this project as it has support for TCP as written in the README file.
I have connected a client to a server and can send messages and receive answers.

In order to make two-way communication between client and server when the client is behind a NAT or firewall without using (the currently unsupported) websockets, I was looking into sending a message from the server to the client by using the already established session, which should be possible as written in the RFC8323 section 3.3 'Message Transmission':

The Transport Connection is bidirectional, so requests can be sent by
both the entity that established the connection (Connection
Initiator) and the remote host (Connection Acceptor).

I can see that there is a makeRequest() method for the server, but I am missing a corresponding addRequestHandler for the client in order to catch the request made by the server.

Is this functionality supported at the moment?
Or am I missing something obvious?

Thanks

Could java-coap using SSL with my own CA certificate?

I am trying the condition that I have my own CA, and I try to use client to use SSL to connect the server with the CA certificate.
How could I implement it, I just could find the test about SSL using the secrete with keystore in this library.

Multicast server example

Hi I have problem with multicast request. I create server

MulticastSocketTransport transport = new MulticastSocketTransport(
                new InetSocketAddress(InetAddress.getByName("224.0.1.187"), 5683),
                "224.0.1.187",
                Executors.newScheduledThreadPool(
                        NetworkConfig.getStandard().getInt(NetworkConfig.Keys.PROTOCOL_STAGE_THREAD_COUNT), 
                        new NamedThreadFactory("CoapServer#")));

        server = CoapServer.builder().transport(transport).build();
        server.addRequestHandler("/cit/s", new SimpleCoapResource());
        server.start();

but every multicast request faild with error message "c.m.coap.server.internal.CoapMessaging : Can not process CoAP message ..."

Can you give me some hint what I do wrong or working example?

thank you for answering my question

Support for broadcast

Hi,

I am sorry if this is not the right place for this question.

Does this library have support for 'broadcast'. If yes, could you please point me to a sample or documentation that could help me create a demo for CoAP broadcast. Thank you.

Message ID can crash the io loop.

In the method DatagramSocketTransport#readingLoop() catches the IllegalArgumentException thrown by setMessageId outside of the loop, effectively crashing the whole server.

Socket Closed when stop()

when I try to test the example
java-coap/coap-core/src/test/java/protocolTests/ClientServerTest.java
(https://github.com/PelionIoT/java-coap/blob/master/coap-core/src/test/java/protocolTests/ClientServerTest.java)

case:
when server.stop() or client.stop(), the console would show "java.net.SocketException: socket closed"

process:
when I traced this process, I found it sources from DatagramSocketTransport.stop() method and LOGGER.error(e.getMessage(), e); in the method, the code line about "TransportExecutors.shutdown(readingWorker);" in this method couldn't run.

Should we deal with it or need to ignore it.

Blockwise transfer

Good morning, I have been working on getting a blockwise transfer working as part of a POST request.

I effectively have a large amount of data I want to send, I want the Java CoAP library to handle the block transfer, and once done have it unblock from the future to be able to obtain the fully reassembled payload.

I have been struggling to get this right, so far this is the code I have going:

/**
* Grab a hold of the resource as a target for our POST.
* 
* Then pack into the request our DLMS xAPDU with the
* DLMS content type.
* 
* Then also set the headers:
*/
String uriHostStr = (this.remoteHost.getAddress()+":"+this.remoteHost.getPort()).replace("/", "");
log.warning("Computed URI host string: '"+uriHostStr+"'");

CoapRequestTarget resourceTarget = this.client.resource(this.resourcePath)
  .payload(payloadToSend, this.contentType)
  .con()
  .host(uriHostStr)
  .token(getAToken());
//  .query("");

// Pack the headers in
resourceTarget = packHeaderOptions(resourceTarget);



log.finer("POST to be sent: '"+resourceTarget+"'");

// Now POST it and wait for it to complete
CompletableFuture<CoapPacket> postFuture = resourceTarget.post(); 

// Wait for the response Coap packet
CoapPacket postResp = postFuture.get();
log.finer("Post response: '"+postResp+"'");

byte[] responsePayload = postResp.getPayload();
log.info("Post payload: '"+Arrays.toString(responsePayload)+"'");

How could I go about this? (Below is attached one of the ways I need to accomplish this)

IMG-20230921-WA0000.jpg

IMG-20230921-WA0001.jpg

Example Server

Hello,

I see there is an example client application included. Is there an example server as well? I couldn't find any. If you guys actually have one but it's not available in the repository for any reason, could I have it in a gist file or something like that?

Thanks!
Bruno Melo.

Timeout trying to connect to arm mbed remote server

We tried to connect to remote server api.connector.mbed.com port 5694 but the connection was not happening and timeout exception was given with token also provided.
We tried in a Copper add-on for firefox, still the same timeout issue happens.
Is the server up and running? Please help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.