/*
- * //****************************************************************** // //
- * Copyright 2016 Samsung Electronics All Rights Reserved. //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // //
- * 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. //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *******************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
- package org.iotivity.cloud.base;
-
- import java.net.URI;
- import java.net.URISyntaxException;
-
- import javax.net.ssl.SSLException;
-
- import io.netty.bootstrap.Bootstrap;
- import io.netty.channel.Channel;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelPipeline;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.SimpleChannelInboundHandler;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioSocketChannel;
- import io.netty.handler.codec.http.ClientCookieEncoder;
- import io.netty.handler.codec.http.DefaultCookie;
- import io.netty.handler.codec.http.DefaultFullHttpRequest;
- import io.netty.handler.codec.http.HttpClientCodec;
- import io.netty.handler.codec.http.HttpContent;
- import io.netty.handler.codec.http.HttpContentDecompressor;
- import io.netty.handler.codec.http.HttpHeaders;
- import io.netty.handler.codec.http.HttpMethod;
- import io.netty.handler.codec.http.HttpObject;
- import io.netty.handler.codec.http.HttpRequest;
- import io.netty.handler.codec.http.HttpResponse;
- import io.netty.handler.codec.http.HttpVersion;
- import io.netty.handler.codec.http.LastHttpContent;
- import io.netty.handler.ssl.SslContext;
- import io.netty.handler.ssl.SslContextBuilder;
- import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
- import io.netty.util.CharsetUtil;
-
- public class HttpClient {
-
- private static class HttpClientInitializer
- extends ChannelInitializer<SocketChannel> {
-
- public static class HttpSnoopClientHandler
- extends SimpleChannelInboundHandler<HttpObject> {
-
- @Override
- public void channelRead0(ChannelHandlerContext ctx,
- HttpObject msg) {
- if (msg instanceof HttpResponse) {
- HttpResponse response = (HttpResponse) msg;
-
- System.err.println("STATUS: " + response.getStatus());
- System.err.println(
- "VERSION: " + response.getProtocolVersion());
- System.err.println();
-
- if (!response.headers().isEmpty()) {
- for (String name : response.headers().names()) {
- for (String value : response.headers()
- .getAll(name)) {
- System.err.println(
- "HEADER: " + name + " = " + value);
- }
- }
- System.err.println();
- }
-
- if (HttpHeaders.isTransferEncodingChunked(response)) {
- System.err.println("CHUNKED CONTENT {");
- } else {
- System.err.println("CONTENT {");
- }
- }
- if (msg instanceof HttpContent) {
- HttpContent content = (HttpContent) msg;
-
- System.err.print(
- content.content().toString(CharsetUtil.UTF_8));
- System.err.flush();
-
- if (content instanceof LastHttpContent) {
- System.err.println("} END OF CONTENT");
- ctx.close();
- }
- }
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx,
- Throwable cause) {
- cause.printStackTrace();
- ctx.close();
- }
- }
-
- private final SslContext sslCtx;
-
- public HttpClientInitializer(SslContext sslCtx) {
- this.sslCtx = sslCtx;
- }
-
- @Override
- public void initChannel(SocketChannel ch) {
- ChannelPipeline p = ch.pipeline();
-
- // Enable HTTPS if necessary.
- if (sslCtx != null) {
- p.addLast(sslCtx.newHandler(ch.alloc()));
- }
-
- p.addLast(new HttpClientCodec());
-
- // Remove the following line if you don't want automatic content
- // decompression.
- p.addLast(new HttpContentDecompressor());
-
- // Uncomment the following line if you don't want to handle
- // HttpContents.
- // p.addLast(new HttpObjectAggregator(1048576));
-
- p.addLast(new HttpSnoopClientHandler());
- }
- }
-
- public void connect(String strUrl)
- throws URISyntaxException, InterruptedException, SSLException {
- URI uri = new URI(strUrl);
-
- String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
- String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
-
- int port = uri.getPort();
-
- if (port == -1) {
- if ("http".equalsIgnoreCase(scheme)) {
- port = 80;
- } else if ("https".equalsIgnoreCase(scheme)) {
- port = 443;
- }
- }
-
- if (!"http".equalsIgnoreCase(scheme)
- && !"https".equalsIgnoreCase(scheme)) {
- return;
- }
-
- final boolean ssl = "https".equalsIgnoreCase(scheme);
- final SslContext sslCtx;
-
- if (ssl) {
- sslCtx = SslContextBuilder.forClient()
- .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
- } else {
- sslCtx = null;
- }
-
- EventLoopGroup group = new NioEventLoopGroup();
-
- try {
- Bootstrap b = new Bootstrap();
- b.group(group);
- b.channel(NioSocketChannel.class);
- b.handler(new HttpClientInitializer(sslCtx));
-
- Channel ch = b.connect(host, port).sync().channel();
-
- HttpRequest request = new DefaultFullHttpRequest(
- HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
- request.headers().set(HttpHeaders.Names.HOST, host);
- request.headers().set(HttpHeaders.Names.CONNECTION,
- HttpHeaders.Values.CLOSE);
- request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING,
- HttpHeaders.Values.GZIP);
-
- request.headers().set(HttpHeaders.Names.COOKIE,
- ClientCookieEncoder.encode(
- new DefaultCookie("my-cookie", "foo"),
- new DefaultCookie("another-cookie", "bar")));
-
- ch.writeAndFlush(request);
-
- ch.closeFuture().sync();
- } finally {
- group.shutdownGracefully();
- }
- }
-
- }
+ // package org.iotivity.cloud.base;
+ //
+ // import java.net.URI;
+ // import java.net.URISyntaxException;
+ //
+ // import javax.net.ssl.SSLException;
+ //
+ // import io.netty.bootstrap.Bootstrap;
+ // import io.netty.channel.Channel;
+ // import io.netty.channel.ChannelHandlerContext;
+ // import io.netty.channel.ChannelInitializer;
+ // import io.netty.channel.ChannelPipeline;
+ // import io.netty.channel.EventLoopGroup;
+ // import io.netty.channel.SimpleChannelInboundHandler;
+ // import io.netty.channel.nio.NioEventLoopGroup;
+ // import io.netty.channel.socket.SocketChannel;
+ // import io.netty.channel.socket.nio.NioSocketChannel;
+ // import io.netty.handler.codec.http.ClientCookieEncoder;
+ // import io.netty.handler.codec.http.DefaultCookie;
+ // import io.netty.handler.codec.http.DefaultFullHttpRequest;
+ // import io.netty.handler.codec.http.HttpClientCodec;
+ // import io.netty.handler.codec.http.HttpContent;
+ // import io.netty.handler.codec.http.HttpContentDecompressor;
+ // import io.netty.handler.codec.http.HttpHeaders;
+ // import io.netty.handler.codec.http.HttpMethod;
+ // import io.netty.handler.codec.http.HttpObject;
+ // import io.netty.handler.codec.http.HttpRequest;
+ // import io.netty.handler.codec.http.HttpResponse;
+ // import io.netty.handler.codec.http.HttpVersion;
+ // import io.netty.handler.codec.http.LastHttpContent;
+ // import io.netty.handler.ssl.SslContext;
+ // import io.netty.handler.ssl.SslContextBuilder;
+ // import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
+ // import io.netty.util.CharsetUtil;
+ //
+ // public class HttpClient {
+ //
+ // private static class HttpClientInitializer
+ // extends ChannelInitializer<SocketChannel> {
+ //
+ // public static class HttpSnoopClientHandler
+ // extends SimpleChannelInboundHandler<HttpObject> {
+ //
+ // @Override
+ // public void channelRead0(ChannelHandlerContext ctx,
+ // HttpObject msg) {
+ // if (msg instanceof HttpResponse) {
+ // HttpResponse response = (HttpResponse) msg;
+ //
+ // System.err.println("STATUS: " + response.getStatus());
+ // System.err.println(
+ // "VERSION: " + response.getProtocolVersion());
+ // System.err.println();
+ //
+ // if (!response.headers().isEmpty()) {
+ // for (String name : response.headers().names()) {
+ // for (String value : response.headers()
+ // .getAll(name)) {
+ // System.err.println(
+ // "HEADER: " + name + " = " + value);
+ // }
+ // }
+ // System.err.println();
+ // }
+ //
+ // if (HttpHeaders.isTransferEncodingChunked(response)) {
+ // System.err.println("CHUNKED CONTENT {");
+ // } else {
+ // System.err.println("CONTENT {");
+ // }
+ // }
+ // if (msg instanceof HttpContent) {
+ // HttpContent content = (HttpContent) msg;
+ //
+ // System.err.print(
+ // content.content().toString(CharsetUtil.UTF_8));
+ // System.err.flush();
+ //
+ // if (content instanceof LastHttpContent) {
+ // System.err.println("} END OF CONTENT");
+ // ctx.close();
+ // }
+ // }
+ // }
+ //
+ // @Override
+ // public void exceptionCaught(ChannelHandlerContext ctx,
+ // Throwable cause) {
+ // cause.printStackTrace();
+ // ctx.close();
+ // }
+ // }
+ //
+ // private final SslContext sslCtx;
+ //
+ // public HttpClientInitializer(SslContext sslCtx) {
+ // this.sslCtx = sslCtx;
+ // }
+ //
+ // @Override
+ // public void initChannel(SocketChannel ch) {
+ // ChannelPipeline p = ch.pipeline();
+ //
+ // // Enable HTTPS if necessary.
+ // if (sslCtx != null) {
+ // p.addLast(sslCtx.newHandler(ch.alloc()));
+ // }
+ //
+ // p.addLast(new HttpClientCodec());
+ //
+ // // Remove the following line if you don't want automatic content
+ // // decompression.
+ // p.addLast(new HttpContentDecompressor());
+ //
+ // // Uncomment the following line if you don't want to handle
+ // // HttpContents.
+ // // p.addLast(new HttpObjectAggregator(1048576));
+ //
+ // p.addLast(new HttpSnoopClientHandler());
+ // }
+ // }
+ //
+ // public void connect(String strUrl)
+ // throws URISyntaxException, InterruptedException, SSLException {
+ // URI uri = new URI(strUrl);
+ //
+ // String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
+ // String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
+ //
+ // int port = uri.getPort();
+ //
+ // if (port == -1) {
+ // if ("http".equalsIgnoreCase(scheme)) {
+ // port = 80;
+ // } else if ("https".equalsIgnoreCase(scheme)) {
+ // port = 443;
+ // }
+ // }
+ //
+ // if (!"http".equalsIgnoreCase(scheme)
+ // && !"https".equalsIgnoreCase(scheme)) {
+ // return;
+ // }
+ //
+ // final boolean ssl = "https".equalsIgnoreCase(scheme);
+ // final SslContext sslCtx;
+ //
+ // if (ssl) {
+ // sslCtx = SslContextBuilder.forClient()
+ // .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
+ // } else {
+ // sslCtx = null;
+ // }
+ //
+ // EventLoopGroup group = new NioEventLoopGroup();
+ //
+ // try {
+ // Bootstrap b = new Bootstrap();
+ // b.group(group);
+ // b.channel(NioSocketChannel.class);
+ // b.handler(new HttpClientInitializer(sslCtx));
+ //
+ // Channel ch = b.connect(host, port).sync().channel();
+ //
+ // HttpRequest request = new DefaultFullHttpRequest(
+ // HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
+ // request.headers().set(HttpHeaders.Names.HOST, host);
+ // request.headers().set(HttpHeaders.Names.CONNECTION,
+ // HttpHeaders.Values.CLOSE);
+ // request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING,
+ // HttpHeaders.Values.GZIP);
+ //
+ // request.headers().set(HttpHeaders.Names.COOKIE,
+ // ClientCookieEncoder.encode(
+ // new DefaultCookie("my-cookie", "foo"),
+ // new DefaultCookie("another-cookie", "bar")));
+ //
+ // ch.writeAndFlush(request);
+ //
+ // ch.closeFuture().sync();
+ // } finally {
+ // group.shutdownGracefully();
+ // }
+ // }
+ //
+ // }
/*
- * //****************************************************************** // //
- * Copyright 2016 Samsung Electronics All Rights Reserved. //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // //
- * 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. //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *******************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
- package org.iotivity.cloud.base;
-
- import java.net.InetSocketAddress;
- import java.security.cert.CertificateException;
- import java.util.ArrayList;
- import java.util.List;
-
- import javax.net.ssl.SSLException;
-
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelHandler;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelPipeline;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
- import io.netty.handler.codec.http.HttpRequestDecoder;
- import io.netty.handler.codec.http.HttpResponseEncoder;
- import io.netty.handler.logging.LogLevel;
- import io.netty.handler.logging.LoggingHandler;
- import io.netty.util.concurrent.GenericFutureListener;
-
- public class HttpServer {
-
- private static class HttpServerInitializer
- extends ChannelInitializer<SocketChannel> {
-
- private List<ChannelHandler> additionalHandlers = new ArrayList<ChannelHandler>();
-
- public HttpServerInitializer() {
- }
-
- public void addHandler(ChannelHandler handler) {
- additionalHandlers.add(handler);
- }
-
- @Override
- public void initChannel(SocketChannel ch) {
- ChannelPipeline p = ch.pipeline();
- /*
- * if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); }
- */
- p.addLast(new HttpRequestDecoder());
- // Uncomment the following line if you don't want to handle
- // HttpChunks.
- // p.addLast(new HttpObjectAggregator(1048576));
- p.addLast(new HttpResponseEncoder());
- // Remove the following line if you don't want automatic content
- // compression.
- // p.addLast(new HttpContentCompressor());
- for (ChannelHandler handler : additionalHandlers) {
- p.addLast(handler);
- }
- }
-
- }
-
- EventLoopGroup bossGroup = new NioEventLoopGroup(1);
-
- EventLoopGroup workerGroup = new NioEventLoopGroup();
-
- HttpServerInitializer initializer = new HttpServerInitializer();
-
- public void addHandler(ChannelHandler handler) {
- initializer.addHandler(handler);
- }
-
- public void startServer(InetSocketAddress inetSocketAddress)
- throws CertificateException, SSLException, InterruptedException {
-
- try {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup);
- b.channel(NioServerSocketChannel.class);
- b.handler(new LoggingHandler(LogLevel.INFO));
-
- b.childHandler(initializer);
-
- ChannelFuture ch = b.bind(inetSocketAddress).sync();
- ch.addListener(new GenericFutureListener<ChannelFuture>() {
-
- @Override
- public void operationComplete(ChannelFuture future)
- throws Exception {
- // TODO Auto-generated method stub
- System.out
- .println("Connection status of TCP Http SERVER : "
- + future.isSuccess());
- }
-
- });
- } finally {
- }
-
- }
-
- public void stopServer() {
- // shut down all event loops
- if (bossGroup != null) {
- bossGroup.shutdownGracefully();
-
- try {
- bossGroup.terminationFuture().sync();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- if (workerGroup != null) {
- workerGroup.shutdownGracefully();
-
- try {
- workerGroup.terminationFuture().sync();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
-
- }
+ // package org.iotivity.cloud.base;
+ //
+ // import java.net.InetSocketAddress;
+ // import java.security.cert.CertificateException;
+ // import java.util.ArrayList;
+ // import java.util.List;
+ //
+ // import javax.net.ssl.SSLException;
+ //
+ // import io.netty.bootstrap.ServerBootstrap;
+ // import io.netty.channel.ChannelFuture;
+ // import io.netty.channel.ChannelHandler;
+ // import io.netty.channel.ChannelInitializer;
+ // import io.netty.channel.ChannelPipeline;
+ // import io.netty.channel.EventLoopGroup;
+ // import io.netty.channel.nio.NioEventLoopGroup;
+ // import io.netty.channel.socket.SocketChannel;
+ // import io.netty.channel.socket.nio.NioServerSocketChannel;
+ // import io.netty.handler.codec.http.HttpRequestDecoder;
+ // import io.netty.handler.codec.http.HttpResponseEncoder;
+ // import io.netty.handler.logging.LogLevel;
+ // import io.netty.handler.logging.LoggingHandler;
+ // import io.netty.util.concurrent.GenericFutureListener;
+ //
+ // public class HttpServer {
+ //
+ // private static class HttpServerInitializer
+ // extends ChannelInitializer<SocketChannel> {
+ //
+ // private List<ChannelHandler> additionalHandlers = new
+ // ArrayList<ChannelHandler>();
+ //
+ // public HttpServerInitializer() {
+ // }
+ //
+ // public void addHandler(ChannelHandler handler) {
+ // additionalHandlers.add(handler);
+ // }
+ //
+ // @Override
+ // public void initChannel(SocketChannel ch) {
+ // ChannelPipeline p = ch.pipeline();
+ // /*
+ // * if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); }
+ // */
+ // p.addLast(new HttpRequestDecoder());
+ // // Uncomment the following line if you don't want to handle
+ // // HttpChunks.
+ // // p.addLast(new HttpObjectAggregator(1048576));
+ // p.addLast(new HttpResponseEncoder());
+ // // Remove the following line if you don't want automatic content
+ // // compression.
+ // // p.addLast(new HttpContentCompressor());
+ // for (ChannelHandler handler : additionalHandlers) {
+ // p.addLast(handler);
+ // }
+ // }
+ //
+ // }
+ //
+ // EventLoopGroup bossGroup = new NioEventLoopGroup(1);
+ //
+ // EventLoopGroup workerGroup = new NioEventLoopGroup();
+ //
+ // HttpServerInitializer initializer = new HttpServerInitializer();
+ //
+ // public void addHandler(ChannelHandler handler) {
+ // initializer.addHandler(handler);
+ // }
+ //
+ // public void startServer(InetSocketAddress inetSocketAddress)
+ // throws CertificateException, SSLException, InterruptedException {
+ //
+ // try {
+ // ServerBootstrap b = new ServerBootstrap();
+ // b.group(bossGroup, workerGroup);
+ // b.channel(NioServerSocketChannel.class);
+ // b.handler(new LoggingHandler(LogLevel.INFO));
+ //
+ // b.childHandler(initializer);
+ //
+ // ChannelFuture ch = b.bind(inetSocketAddress).sync();
+ // ch.addListener(new GenericFutureListener<ChannelFuture>() {
+ //
+ // @Override
+ // public void operationComplete(ChannelFuture future)
+ // throws Exception {
+ // // TODO Auto-generated method stub
+ // System.out
+ // .println("Connection status of TCP Http SERVER : "
+ // + future.isSuccess());
+ // }
+ //
+ // });
+ // } finally {
+ // }
+ //
+ // }
+ //
+ // public void stopServer() {
+ // // shut down all event loops
+ // if (bossGroup != null) {
+ // bossGroup.shutdownGracefully();
+ //
+ // try {
+ // bossGroup.terminationFuture().sync();
+ // } catch (InterruptedException e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // }
+ // }
+ //
+ // if (workerGroup != null) {
+ // workerGroup.shutdownGracefully();
+ //
+ // try {
+ // workerGroup.terminationFuture().sync();
+ // } catch (InterruptedException e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // }
+ // }
+ // }
+ //
+ // }
}
public void clearUriPath() {
- uri_path.clear();
- }
-
- public void setAccept(byte[] accepts) {
- accept = accepts;
+ if (uri_path != null) {
+ uri_path.clear();
+ }
}
-}
+}
/*
- * //****************************************************************** // //
- * Copyright 2016 Samsung Electronics All Rights Reserved. //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // //
- * 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. //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *******************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
- package org.iotivity.cloud.base.protocols.proxy;
-
- import java.nio.charset.StandardCharsets;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map.Entry;
-
- import org.iotivity.cloud.base.SessionManager;
- import org.iotivity.cloud.base.protocols.coap.CoapRequest;
- import org.iotivity.cloud.base.protocols.coap.CoapResponse;
- import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
- import org.iotivity.cloud.util.Cbor;
- import org.iotivity.cloud.util.Logger;
-
- import io.netty.buffer.Unpooled;
- import io.netty.channel.ChannelDuplexHandler;
- import io.netty.channel.ChannelFutureListener;
- import io.netty.channel.ChannelHandler.Sharable;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.handler.codec.http.DefaultFullHttpResponse;
- import io.netty.handler.codec.http.HttpHeaders;
- import io.netty.handler.codec.http.HttpMethod;
- import io.netty.handler.codec.http.HttpRequest;
- import io.netty.handler.codec.http.HttpResponse;
- import io.netty.handler.codec.http.HttpResponseStatus;
- import io.netty.handler.codec.http.HttpVersion;
- import io.netty.handler.codec.http.QueryStringDecoder;
- import io.netty.util.AttributeKey;
- import io.netty.util.CharsetUtil;
-
- @Sharable
- public class CoapHttpProxyHandler extends ChannelDuplexHandler {
-
- // Proxy converts http request to coaprequest and coapresponse to
- // httpresponse
- private SessionManager sessionManager = null;
-
- private static final AttributeKey<ChannelHandlerContext> keyHttpCtx = AttributeKey
- .newInstance("httpCtx");
-
- public CoapHttpProxyHandler(SessionManager sessionManager) {
- this.sessionManager = sessionManager;
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg)
- throws Exception {
-
- // in case of Receive Request from http
- if (msg instanceof HttpRequest) {
- // Check uri query param that contains coap device uuid
- // then search those and create coapRequest and send
- HttpRequest httpRequest = (HttpRequest) msg;
- QueryStringDecoder queryStringDecoder = new QueryStringDecoder(
- httpRequest.getUri());
-
- List<String> didList = queryStringDecoder.parameters().get("di");
-
- if (didList != null) {
- ChannelHandlerContext coapClient = sessionManager
- .querySession(didList.get(0));
-
- if (coapClient != null) {
- List<String> uriList = queryStringDecoder.parameters()
- .get("href");
- if (uriList != null) {
- coapClient.channel().attr(keyHttpCtx).set(ctx);
- coapClient.writeAndFlush(httpRequestToCoAPRequest(
- uriList.get(0), (HttpRequest) msg));
-
- return;
- }
- } else {
- Logger.d("Unable to find session: " + didList.get(0));
- }
- }
-
- // Prints available sessions to html
-
- ctx.writeAndFlush(printsAvailableSessions())
- .addListener(ChannelFutureListener.CLOSE);
- return;
- }
-
- if (msg instanceof CoapResponse) {
- ctx.channel().attr(keyHttpCtx).get()
- .writeAndFlush(
- coapResponseToHttpResponse((CoapResponse) msg))
- .addListener(ChannelFutureListener.CLOSE);
- return;
- }
-
- // Pass to upper-layer
- super.channelRead(ctx, msg);
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- cause.printStackTrace();
- ctx.close();
- }
-
- HttpResponse printsAvailableSessions() {
-
- StringBuilder strBuilder = new StringBuilder();
- List<String> sessions = sessionManager.getSessions();
-
- strBuilder.append("<html>");
- strBuilder.append("<b>Available sessions</b><br>");
-
- for (String session : sessions) {
- strBuilder.append(session);
- strBuilder.append("<br>");
- }
-
- strBuilder.append("</html>");
-
- HttpResponse response = new DefaultFullHttpResponse(
- HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
- Unpooled.copiedBuffer(strBuilder.toString(),
- CharsetUtil.UTF_8));
- response.headers().set(HttpHeaders.Names.CONTENT_TYPE,
- "text/html; charset=UTF-8");
-
- return response;
- }
-
- HttpResponse httpRequestToSendError() {
- HttpResponse response = new DefaultFullHttpResponse(
- HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND,
- Unpooled.copiedBuffer(
- "Failure: " + HttpResponseStatus.NOT_FOUND + "\r\n",
- CharsetUtil.UTF_8));
- response.headers().set(HttpHeaders.Names.CONTENT_TYPE,
- "text/html; charset=UTF-8");
-
- return response;
- }
-
- CoapRequest httpRequestToCoAPRequest(String uri, HttpRequest httpRequest) {
- CoapRequest coapRequest;
-
- // TODO: coapRequest converter required
- // coapRequest.getOptions().setUriQuery();
- if (httpRequest.getMethod() == HttpMethod.GET) {
- coapRequest = new CoapRequest(CoapMethod.GET);
- } else if (httpRequest.getMethod() == HttpMethod.PUT) {
- coapRequest = new CoapRequest(CoapMethod.PUT);
- } else if (httpRequest.getMethod() == HttpMethod.POST) {
- coapRequest = new CoapRequest(CoapMethod.POST);
- } else if (httpRequest.getMethod() == HttpMethod.DELETE) {
- coapRequest = new CoapRequest(CoapMethod.DELETE);
- } else {
- throw new IllegalArgumentException();
- }
-
- coapRequest.setUriPath(uri);
-
- return coapRequest;
- }
-
- HttpResponse coapResponseToHttpResponse(CoapResponse coapResponse) {
-
- Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
-
- HashMap<String, Object> rep = cbor
- .parsePayloadFromCbor(coapResponse.getPayload(), HashMap.class);
-
- StringBuilder strBuilder = new StringBuilder();
-
- for (Entry<String, Object> entry : rep.entrySet()) {
- String key = entry.getKey();
- String value = entry.getValue().toString();
- strBuilder.append("Key: " + key + " Value: " + value + "<br>");
- }
-
- HttpResponse httpResponse = new DefaultFullHttpResponse(
- HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
- Unpooled.wrappedBuffer(strBuilder.toString().getBytes(StandardCharsets.UTF_8)));
-
- httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE,
- "text/html; charset=UTF-8");
-
- // TODO: httpResponse converter required
-
- return httpResponse;
- }
- }
+ // package org.iotivity.cloud.base.protocols.proxy;
+ //
+ // import java.nio.charset.StandardCharsets;
+ // import java.util.HashMap;
+ // import java.util.List;
+ // import java.util.Map.Entry;
+ //
+ // import org.iotivity.cloud.base.SessionManager;
+ // import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+ // import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+ // import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
+ // import org.iotivity.cloud.util.Cbor;
+ // import org.iotivity.cloud.util.Logger;
+ //
+ // import io.netty.buffer.Unpooled;
+ // import io.netty.channel.ChannelDuplexHandler;
+ // import io.netty.channel.ChannelFutureListener;
+ // import io.netty.channel.ChannelHandler.Sharable;
+ // import io.netty.channel.ChannelHandlerContext;
+ // import io.netty.handler.codec.http.DefaultFullHttpResponse;
+ // import io.netty.handler.codec.http.HttpHeaders;
+ // import io.netty.handler.codec.http.HttpMethod;
+ // import io.netty.handler.codec.http.HttpRequest;
+ // import io.netty.handler.codec.http.HttpResponse;
+ // import io.netty.handler.codec.http.HttpResponseStatus;
+ // import io.netty.handler.codec.http.HttpVersion;
+ // import io.netty.handler.codec.http.QueryStringDecoder;
+ // import io.netty.util.AttributeKey;
+ // import io.netty.util.CharsetUtil;
+ //
+ // @Sharable
+ // public class CoapHttpProxyHandler extends ChannelDuplexHandler {
+ //
+ // // Proxy converts http request to coaprequest and coapresponse to
+ // // httpresponse
+ // private SessionManager sessionManager = null;
+ //
+ // private static final AttributeKey<ChannelHandlerContext> keyHttpCtx =
+ // AttributeKey
+ // .newInstance("httpCtx");
+ //
+ // public CoapHttpProxyHandler(SessionManager sessionManager) {
+ // this.sessionManager = sessionManager;
+ // }
+ //
+ // @Override
+ // public void channelRead(ChannelHandlerContext ctx, Object msg)
+ // throws Exception {
+ //
+ // // in case of Receive Request from http
+ // if (msg instanceof HttpRequest) {
+ // // Check uri query param that contains coap device uuid
+ // // then search those and create coapRequest and send
+ // HttpRequest httpRequest = (HttpRequest) msg;
+ // QueryStringDecoder queryStringDecoder = new QueryStringDecoder(
+ // httpRequest.getUri());
+ //
+ // List<String> didList = queryStringDecoder.parameters().get("di");
+ //
+ // if (didList != null) {
+ // ChannelHandlerContext coapClient = sessionManager
+ // .querySession(didList.get(0));
+ //
+ // if (coapClient != null) {
+ // List<String> uriList = queryStringDecoder.parameters()
+ // .get("href");
+ // if (uriList != null) {
+ // coapClient.channel().attr(keyHttpCtx).set(ctx);
+ // coapClient.writeAndFlush(httpRequestToCoAPRequest(
+ // uriList.get(0), (HttpRequest) msg));
+ //
+ // return;
+ // }
+ // } else {
+ // Logger.d("Unable to find session: " + didList.get(0));
+ // }
+ // }
+ //
+ // // Prints available sessions to html
+ //
+ // ctx.writeAndFlush(printsAvailableSessions())
+ // .addListener(ChannelFutureListener.CLOSE);
+ // return;
+ // }
+ //
+ // if (msg instanceof CoapResponse) {
+ // ctx.channel().attr(keyHttpCtx).get()
+ // .writeAndFlush(
+ // coapResponseToHttpResponse((CoapResponse) msg))
+ // .addListener(ChannelFutureListener.CLOSE);
+ // return;
+ // }
+ //
+ // // Pass to upper-layer
+ // super.channelRead(ctx, msg);
+ // }
+ //
+ // @Override
+ // public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+ // cause.printStackTrace();
+ // ctx.close();
+ // }
+ //
+ // HttpResponse printsAvailableSessions() {
+ //
+ // StringBuilder strBuilder = new StringBuilder();
+ // List<String> sessions = sessionManager.getSessions();
+ //
+ // strBuilder.append("<html>");
+ // strBuilder.append("<b>Available sessions</b><br>");
+ //
+ // for (String session : sessions) {
+ // strBuilder.append(session);
+ // strBuilder.append("<br>");
+ // }
+ //
+ // strBuilder.append("</html>");
+ //
+ // HttpResponse response = new DefaultFullHttpResponse(
+ // HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
+ // Unpooled.copiedBuffer(strBuilder.toString(),
+ // CharsetUtil.UTF_8));
+ // response.headers().set(HttpHeaders.Names.CONTENT_TYPE,
+ // "text/html; charset=UTF-8");
+ //
+ // return response;
+ // }
+ //
+ // HttpResponse httpRequestToSendError() {
+ // HttpResponse response = new DefaultFullHttpResponse(
+ // HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND,
+ // Unpooled.copiedBuffer(
+ // "Failure: " + HttpResponseStatus.NOT_FOUND + "\r\n",
+ // CharsetUtil.UTF_8));
+ // response.headers().set(HttpHeaders.Names.CONTENT_TYPE,
+ // "text/html; charset=UTF-8");
+ //
+ // return response;
+ // }
+ //
+ // CoapRequest httpRequestToCoAPRequest(String uri, HttpRequest httpRequest) {
+ // CoapRequest coapRequest;
+ //
+ // // TODO: coapRequest converter required
+ // // coapRequest.getOptions().setUriQuery();
+ // if (httpRequest.getMethod() == HttpMethod.GET) {
+ // coapRequest = new CoapRequest(CoapMethod.GET);
+ // } else if (httpRequest.getMethod() == HttpMethod.PUT) {
+ // coapRequest = new CoapRequest(CoapMethod.PUT);
+ // } else if (httpRequest.getMethod() == HttpMethod.POST) {
+ // coapRequest = new CoapRequest(CoapMethod.POST);
+ // } else if (httpRequest.getMethod() == HttpMethod.DELETE) {
+ // coapRequest = new CoapRequest(CoapMethod.DELETE);
+ // } else {
+ // throw new IllegalArgumentException();
+ // }
+ //
+ // coapRequest.setUriPath(uri);
+ //
+ // return coapRequest;
+ // }
+ //
+ // HttpResponse coapResponseToHttpResponse(CoapResponse coapResponse) {
+ //
+ // Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
+ //
+ // HashMap<String, Object> rep = cbor
+ // .parsePayloadFromCbor(coapResponse.getPayload(), HashMap.class);
+ //
+ // StringBuilder strBuilder = new StringBuilder();
+ //
+ // for (Entry<String, Object> entry : rep.entrySet()) {
+ // String key = entry.getKey();
+ // String value = entry.getValue().toString();
+ // strBuilder.append("Key: " + key + " Value: " + value + "<br>");
+ // }
+ //
+ // HttpResponse httpResponse = new DefaultFullHttpResponse(
+ // HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
+ // Unpooled.wrappedBuffer(strBuilder.toString()
+ // .getBytes(StandardCharsets.UTF_8)));
+ //
+ // httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE,
+ // "text/html; charset=UTF-8");
+ //
+ // // TODO: httpResponse converter required
+ //
+ // return httpResponse;
+ // }
+ // }
errno = 0;
size_t sizeValue = sizeof(value);
int strRet = snprintf(value, sizeValue, "%d", level);
- if (strRet < 0 || (size_t)strRet >= sizeValue)
++
+ if (strRet < 0 || strRet >= (int)sizeValue)
{
OIC_LOG_V(ERROR, TAG, "Failed to parse string due to errno: %d", errno);
exit(1);
jobject CAEDRNativeListen(JNIEnv *env);
/**
-- * This function will listen the connection from remote device.
-- * @param[in] env JNI interface pointer.
-- * @param[in] socket server socket object.
-- * @return JNI_TRUE or JNI_FALSE.
-- */
--jboolean CAEDRIsConnectedForSocket(JNIEnv *env, jobject socket);
--
--/**
* This function will accept the connection from remote device.
* @param[in] env JNI interface pointer.
* @param[in] severSocketObject server socket object.
OIC_LOG(DEBUG, TAG, "start to connect LE");
jobject gatt = CALEClientConnect(env, device,
- CALEClientGetAutoConnectFlag(env, jni_address));
+ CALEClientGetFlagFromState(env, jni_address,
+ CA_LE_AUTO_CONNECT_FLAG));
++
if (NULL == gatt)
{
OIC_LOG(ERROR, TAG, "CALEClientConnect has failed");
return CA_STATUS_FAILED;
}
- if (STATE_CHARACTER_NO_CHANGE == state->notificationState)
+ switch(state_type)
{
- state->notificationState = curState->notificationState;
+ case CA_LE_CONNECTION_STATE:
+ curState->connectedState = target_state;
+ break;
+ case CA_LE_SEND_STATE:
+ curState->sendState = target_state;
+ break;
+ default:
+ break;
+ }
+ OIC_LOG_V(INFO, TAG, "update state - addr : %s, conn : %d, send : %d, ACFlag : %d",
+ curState->address, curState->connectedState, curState->sendState,
+ curState->autoConnectFlag);
+ }
+ else /** state is added newly **/
+ {
+ if (strlen(address) > CA_MACADDR_SIZE)
+ {
+ OIC_LOG(ERROR, TAG, "address is not proper");
+ ca_mutex_unlock(g_deviceStateListMutex);
+ return CA_STATUS_INVALID_PARAM;
}
- state->autoConnectFlag = curState->autoConnectFlag;
- // delete previous state for update new state
- CAResult_t res = CALEClientRemoveDeviceState(state->address);
- if (CA_STATUS_OK != res)
+ CALEState_t *newstate = (CALEState_t*) OICCalloc(1, sizeof(*newstate));
+ if (!newstate)
{
- OIC_LOG(ERROR, TAG, "CALEClientRemoveDeviceState has failed");
+ OIC_LOG(ERROR, TAG, "out of memory");
ca_mutex_unlock(g_deviceStateListMutex);
- return res;
+ return CA_MEMORY_ALLOC_FAILED;
}
- }
- u_arraylist_add(g_deviceStateList, state); // update new state
- OIC_LOG_V(INFO, TAG, "Set State Info to List : %d, %d, %s, %d",
- state->connectedState, state->notificationState,
- state->address, state->autoConnectFlag);
-
+ OICStrcpy(newstate->address, sizeof(newstate->address), address);
+
+ switch(state_type)
+ {
+ case CA_LE_CONNECTION_STATE:
+ newstate->connectedState = target_state;
+ newstate->sendState = STATE_SEND_NONE;
+ break;
+ case CA_LE_SEND_STATE:
+ newstate->connectedState = STATE_DISCONNECTED;
+ newstate->sendState = target_state;
+ break;
+ default:
+ break;
+ }
+ OIC_LOG_V(INFO, TAG, "add a new state to List - addr : %s, "
+ "conn : %d, send : %d, ACFlag : %d",
+ newstate->address, newstate->connectedState, newstate->sendState,
+ newstate->autoConnectFlag);
+ u_arraylist_add(g_deviceStateList, newstate); // update new state
+ }
ca_mutex_unlock(g_deviceStateListMutex);
+
return CA_STATUS_OK;
}
OIC_LOG(DEBUG, TAG, "ifitem is null");
return;
}
-
- applyMulticastToInterface6(ifitem->index);
- struct in_addr inaddr = { .s_addr = ifitem->ipv4addr };
- applyMulticastToInterface4(inaddr);
-}
-static void CAHandleNetlink()
-{
-#ifdef __linux__
- char buf[4096];
- struct nlmsghdr *nh;
- struct sockaddr_nl sa;
- struct iovec iov = { buf, sizeof (buf) };
- struct msghdr msg = { (void *)&sa, sizeof (sa), &iov, 1, NULL, 0, 0 };
-
- size_t len = recvmsg(caglobals.ip.netlinkFd, &msg, 0);
-
- for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len))
+ if (ifitem->family == AF_INET6)
{
- if (nh != NULL && nh->nlmsg_type != RTM_NEWLINK)
- {
- continue;
- }
-
- struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh);
- if (!ifi || (ifi->ifi_flags & IFF_LOOPBACK) || !(ifi->ifi_flags & IFF_RUNNING))
- {
- continue;
- }
-
- int newIndex = ifi->ifi_index;
-
- u_arraylist_t *iflist = CAIPGetInterfaceInformation(newIndex);
- if (!iflist)
- {
- OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
- return;
- }
-
- uint32_t listLength = u_arraylist_length(iflist);
- for (uint32_t i = 0; i < listLength; i++)
- {
- CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
- if (!ifitem)
- {
- continue;
- }
-
- if ((int)ifitem->index != newIndex)
- {
- continue;
- }
-
- CAProcessNewInterface(ifitem);
- break; // we found the one we were looking for
- }
- u_arraylist_destroy(iflist);
+ applyMulticastToInterface6(ifitem->index);
+ }
+ if (ifitem->family == AF_INET)
+ {
+ struct in_addr inaddr = { .s_addr = ifitem->ipv4addr };
+ applyMulticastToInterface4(inaddr);
}
-#endif // __linux__
}
- static void CAHandleNetlink()
- {
- }
void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
{
static void CASelectReturned(fd_set *readFds, int ret)
{
- (void)ret;
+ VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
- if (g_acceptServerFD != -1 && FD_ISSET(g_acceptServerFD, readFds))
+ if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
+ {
+ CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
+ return;
+ }
+ else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
+ {
+ CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
+ return;
+ }
+ else if (-1 != caglobals.tcp.connectionFds[0] &&
+ FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
{
- CAAcceptConnection();
+ // new connection was created from remote device.
+ // exit the function to update read file descriptor.
+ char buf[MAX_ADDR_STR_SIZE_CA] = {0};
+ ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
+ if (-1 == len)
+ {
+ return;
+ }
+ OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
+ FD_CLR(caglobals.tcp.connectionFds[0], readFds);
return;
}
+ else if (-1 != caglobals.tcp.connectionFds[0] &&
+ FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
+ {
+ // new connection was created from remote device.
+ // exit the function to update read file descriptor.
+ char buf[MAX_ADDR_STR_SIZE_CA] = {0};
+ ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
+ if (-1 == len)
+ {
+ return;
+ }
+ OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
+ FD_CLR(caglobals.tcp.connectionFds[0], readFds);
+ return;
+ }
else
{
uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
* This method sends unicast request to AMS service to get ACL for
* the Subject and/or Resource. It sends unicast request such as
* /oic/sec/acl?sub="subjectId";rsrc="/a/led" to get the ACL for
- * the subject & resource
+ * the subject & resource.
*
- * @param context Policy engine context.
+ * @param context is the policy engine context.
*
- * @retval
- * OC_STACK_OK If able to successfully send unicast ACL request
- * OC_STACK_ERROR If unable to successfully send unicast ACL request due to error
+ * @return ::OC_STACK_OK, If able to successfully send unicast ACL request.
+ * ::OC_STACK_ERROR, If unable to successfully send unicast ACL request due to error.
*
*/
- OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType,
- uint16_t securedPort);
+ OCStackResult SendAclReq(PEContext_t *context,
+ OCDevAddr *devAddr,
+ OCConnectivityType connType,
+ uint16_t securedPort);
/*
- * Cleanup CARequestInfo_t object.
- *
- * @param requestInfo is the pointer to @ref CARequestInfo_t.
- */
-void FreeCARequestInfo(CARequestInfo_t *requestInfo);
-
-/*
* This method is used by Policy engine to checks Amacl resource.
* If Amacl is found then it fills up context->amsMgrContext->amsDeviceId
* with amsID of the Amacl else leaves it empty.
*/
OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
OicSecAcl_t *acl, OCProvisionResultCB resultCallback);
+
+ #ifdef __WITH_X509__
+ /**
+ * API to send CRL information to resource.
+ *
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] crl CRL to provision.
+ * @param[in] resultCallback callback provided by API user, callback will be called when
+ * provisioning request recieves a response from resource server.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
+ OicSecCrl_t *crl, OCProvisionResultCB resultCallback);
+ #endif // __WITH_X509__
+ /**
+ * API to send Direct-Pairing Configuration to a device.
+ *
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] pconf PCONF pointer.
+ * @param[in] resultCallback callback provided by API user, callback will be called when
+ * provisioning request recieves a response from resource server.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+ OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
++ OicSecPconf_t *pconf, OCProvisionResultCB resultCallback);
+
+/**
+ * API to send Direct-Pairing Configuration to a device.
+ *
+ * @param[in] selectedDeviceInfo Selected target device.
+ * @param[in] pconf PCONF pointer.
+ * @param[in] resultCallback callback provided by API user, callback will be called when
+ * provisioning request recieves a response from resource server.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
OicSecPconf_t *pconf, OCProvisionResultCB resultCallback);
/**
{
OCStackResult ret = OC_STACK_ERROR;
+ if (!context->amsMgrContext)
+ {
+ goto exit;
+ }
+
//The AmsMgr context endpoint and requestInfo will be free from ,
//AmsMgrAclReqCallback function
- if(context->amsMgrContext->endpoint)
+ if (context->amsMgrContext->endpoint)
{
OICFree(context->amsMgrContext->endpoint);
context->amsMgrContext->endpoint = NULL;
//Secure Virtual Resource database for Iotivity Client application\r
//It contains Client's Identity and the PSK credentials\r
//of other devices which the client trusts\r
- static char CRED_FILE[] = "oic_svr_db_client_directpairing.json";\r
-static char CRED_FILE[] = "oic_svr_db_client_directpairing.dat";\r
--\r
++static char CRED_FILE[] = "oic_svr_db_client_directpairing.dat";
++
static const OCDPDev_t *discoveredDevs = NULL;\r
static const OCDPDev_t *pairedDevs = NULL;\r
\r
OIC_LOG(ERROR, TAG, "Invalid PIN");\r
continue;\r
}\r
- sscanf(input, "%9s", pinNumber);\r
- sscanf(input, "%8s", pinNumber);\r
-- printf("\n");\r
++ sscanf(input, "%8s", pinNumber);
++ printf("\n");
\r
ret = DoDirectPairing(peer, pmSel, pinNumber);\r
if (OC_STACK_OK != ret)\r
\r
return 0;\r
}\r
--\r
--\r
--\r
-{\r
+{
- "acl": [
- {
- "sub": "Kg==",
- "rsrc": [
- "/oic/res",
- "/oic/res/d",
- "/oic/res/types/d",
- "/oic/presence"
- ],
- "perms": 2,
- "ownrs" : [
- "ZGlyZWN0cGFpcmluZ0Rldg=="
- ]
- },
- {
- "sub": "Kg==",
- "rsrc": [
- "/oic/sec/doxm",
- "/oic/sec/pstat",
- "/oic/sec/acl",
- "/oic/sec/cred"
- ],
- "perms": 6,
- "ownrs" : [
- "ZGlyZWN0cGFpcmluZ0Rldg=="
- ]
- }
- ],
- "pstat": {
- "isop": false,
- "deviceid": "ZGlyZWN0cGFpcmluZ0Rldg==",
- "commithash": 0,
- "cm": 0,
- "tm": 0,
- "om": 3,
- "sm": [3]
- },
- "doxm": {
- "oxm": [0],
- "oxmsel": 0,
- "sct": 1,
- "owned": false,
- "deviceid": "ZGlyZWN0cGFpcmluZ0Rldg=="
- }
- }
+ "acl": {\r
+ "aclist": {\r
+ "aces": [\r
+ {\r
+ "subjectuuid": "*",\r
+ "resources": [\r
+ {\r
+ "href": "/oic/res",\r
+ "rel": "",\r
+ "rt": "",\r
+ "if": ""\r
+ },\r
+ {\r
+ "href": "/oic/d",\r
+ "rel": "",\r
+ "rt": "",\r
+ "if": ""\r
+ },\r
+ {\r
+ "href": "/oic/p",\r
+ "rel": "",\r
+ "rt": "",\r
+ "if": ""\r
+ },\r
+ {\r
+ "href": "/oic/res/d",\r
+ "rel": "",\r
+ "rt": "",\r
+ "if": ""\r
+ },\r
+ {\r
+ "href": "/oic/res/types/d",\r
+ "rel": "",\r
+ "rt": "",\r
+ "if": ""\r
+ },\r
+ {\r
+ "href": "/oic/presence",\r
+ "rel": "",\r
+ "rt": "",\r
+ "if": ""\r
+ }\r
+ ],\r
+ "permission": 2\r
+ },\r
+ {\r
+ "subjectuuid": "*",\r
+ "resources": [\r
+ {\r
+ "href": "/oic/sec/doxm",\r
+ "rel": "",\r
+ "rt": "",\r
+ "if": ""\r
+ },\r
+ {\r
+ "href": "/oic/sec/pstat",\r
+ "rel": "",\r
+ "rt": "",\r
+ "if": ""\r
+ },\r
+ {\r
+ "href": "/oic/sec/acl",\r
+ "rel": "",\r
+ "rt": "",\r
+ "if": ""\r
+ },\r
+ {\r
+ "href": "/oic/sec/cred",\r
+ "rel": "",\r
+ "rt": "",\r
+ "if": ""\r
+ }\r
+ ],\r
+ "permission": 6\r
+ }\r
+ ]\r
+ },\r
+ "rowneruuid" : "64697265-6374-7061-6972-696e67446576"\r
+ },\r
+ "pstat": {\r
+ "isop": false,\r
+ "deviceuuid": "64697265-6374-7061-6972-696e67446576",\r
+ "rowneruuid": "64697265-6374-7061-6972-696e67446576",\r
+ "cm": 2,\r
+ "tm": 0,\r
+ "om": 3,\r
+ "sm": 3\r
+ },\r
+ "doxm": {\r
+ "oxms": [0],\r
+ "oxmsel": 0,\r
+ "sct": 1,\r
+ "owned": false,\r
+ "deviceuuid": "64697265-6374-7061-6972-696e67446576",\r
+ "devowneruuid": "",\r
+ "rowneruuid": "64697265-6374-7061-6972-696e67446576",\r
+ "dpc": false\r
+ }\r
+ }\r
CborValue curVal;
// Resource Type
err = cbor_value_map_find_value(rootValue, OC_RSRVD_RESOURCE_TYPE, &curVal);
+ VERIFY_CBOR_SUCCESS(TAG, err, "to find resource type tag");
++
if (cbor_value_is_valid(&curVal))
{
err = OCParseStringLL(rootValue, OC_RSRVD_RESOURCE_TYPE, &out->types);
// Resource type
err = cbor_value_map_find_value(rootValue, OC_RSRVD_RESOURCE_TYPE, &repVal);
+ VERIFY_CBOR_SUCCESS(TAG, err, "to find resource type tag");
++
if(cbor_value_is_valid(&repVal))
{
err = cbor_value_dup_text_string(&repVal, &rt, &len, NULL);
// Interface Types
err = cbor_value_map_find_value(rootValue, OC_RSRVD_INTERFACE, &repVal);
+ VERIFY_CBOR_SUCCESS(TAG, err, "to find interface tag");
++
if(cbor_value_is_valid(&repVal))
{
err = OCParseStringLL(rootValue, OC_RSRVD_INTERFACE, &interfaces);
static CborError OCParseArray(OCRepPayload *out, const char *name, CborValue *container)
{
void *arr = NULL;
- OCRepPayloadPropType type;
- size_t dimensions[MAX_REP_ARRAY_DEPTH];
++
+ OCRepPayloadPropType type = OCREP_PROP_NULL;
+ size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
++
size_t dimTotal = 0;
size_t allocSize = 0;
bool res = true;
OCDiscoveryPayload *discPayload = (OCDiscoveryPayload *)payload;
discPayload->sid = (char *)OICCalloc(1, UUID_STRING_SIZE);
VERIFY_NON_NULL(discPayload->sid, ERROR, OC_STACK_NO_MEMORY);
- memcpy(discPayload->sid, OCGetServerInstanceIDString(), UUID_STRING_SIZE);
++
+ const char* uid = OCGetServerInstanceIDString();
- if(uid)
++ if (uid)
+ {
+ memcpy(discPayload->sid, uid, UUID_STRING_SIZE);
+ }
+
if (!resourceTypeQuery && interfaceQuery && (0 == strcmp(interfaceQuery, OC_RSRVD_INTERFACE_LL)))
{
for (; resource && discoveryResult == OC_STACK_OK; resource = resource->next)
OIC_LOG(ERROR, TAG, "Invalid parameters");
return OC_STACK_INVALID_PARAM;
}
-
-- if(NULL == resultCallback)
++ if (NULL == resultCallback)
{
- OIC_LOG(ERROR, TAG, "Invalid parameters");
+ OIC_LOG(ERROR, TAG, "Invalid callback");
return OC_STACK_INVALID_CALLBACK;
}
+
gDirectpairingCallback = resultCallback;
return DPDirectPairing((OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
pinNumber, DirectPairingCB);
# with spaces.
INPUT = . \
- ../include/OCApi.h \
- ../include/OCPlatform.h \
- ../include/OCRepresentation.h \
- ../include/OCResourceRequest.h \
- ../include/OCResourceResponse.h \
- ../include/OCResource.h \
- ../include/OCProvisioningManager.h \
- ../csdk/stack/include/octypes.h \
- ../csdk/stack/include/ocstackconfig.h \
+ ../../include/OCApi.h \
+ ../../include/OCPlatform.h \
+ ../../include/OCRepresentation.h \
+ ../../include/OCResourceRequest.h \
+ ../../include/OCResourceResponse.h \
+ ../../include/OCResource.h \
+ ../../include/OCProvisioningManager.h \
+ ../../csdk/stack/include/octypes.h \
+ ../../csdk/stack/include/ocstackconfig.h \
guides \
- ../../service/resource-encapsulation/include \
- ../../service/resource-hosting/include \
- ../../service/resource-container/include \
- ../../service/resource-container/bundle-api/include \
- ../../service/things-manager/sdk/inc/ThingsConfiguration.h \
- ../../service/things-manager/sdk/inc/ThingsMaintenance.h \
- ../../service/easy-setup/mediator/richsdk/inc/ \
- ../../service/easy-setup/enrollee/inc \
- ../../service/easy-setup/enrollee/src/softap.h \
- ../../service/easy-setup/inc \
- ../../service/resource-directory/include \
- ../../service/scene-manager/include \
-
+ ../../../service/resource-encapsulation/include \
+ ../../../service/resource-hosting/include \
+ ../../../service/resource-container/include \
+ ../../../service/resource-container/bundle-api/include \
+ ../../../service/things-manager/sdk/inc/ThingsConfiguration.h \
+ ../../../service/things-manager/sdk/inc/ThingsMaintenance.h \
+ ../../../service/easy-setup/mediator/richsdk/inc/ \
+ ../../../service/easy-setup/inc \
+ ../../../service/scene-manager/include \
-
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
# also the default input encoding. Doxygen uses libiconv (or the iconv built
/**
* @file
*
-- * This file contains private internal callback function
++ * This file contains private internal callback function
* prototypes for Easy setup [Enrollee]
*/
/**
* It will return Device which is creating Soft AP.
* i.e.Enrollee or Mediator.
-- * This decesion is based on, what is the value set for ES_SOFTAP_MODE in build command as well as
++ * This decision is based on, what is the value set for ES_SOFTAP_MODE in build command as well as
* in iotivity.spec file.
*/
DeviceRole ESSoftapHost()
};
//callbacks
- void OCProvisioningStatusCallback(EasySetupInfo *easySetupInfo) {
- OC_UNUSED(easySetupInfo);
-void OCProvisioningStatusCallback(EasySetupInfo *easySetupInfo)
++void OCProvisioningStatusCallback(EasySetupInfo *easySetupInfo)
+ {
+ (void) easySetupInfo;
}
/* Test cases for prov_adapter*/
easy_setup_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
if target_os in ['linux']:
-- easy_setup_env.AppendUnique(LIBS = ['pthread', 'dl'])
++ easy_setup_env.AppendUnique(LIBS = ['pthread', 'dl', 'coap'])
if target_os in ['android']:
easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
easy_setup_env.AppendUnique(CXXFLAGS = ['-pthread'])
- easy_setup_env.PrependUnique(LIBS = ['coap'])
- easy_setup_env.AppendUnique(LIBS = ['connectivity_abstraction'])
- easy_setup_env.AppendUnique(LIBS = ['oc_logger'])
- easy_setup_env.AppendUnique(LIBS = ['octbstack'])
- easy_setup_env.AppendUnique(LIBS = ['oc'])
- easy_setup_env.AppendUnique(LIBS = ['pthread'])
- easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
++ easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger'])
if env.get('SECURED') == '1':
easy_setup_env.AppendUnique(LIBS = ['ocpmapi', 'ocprovision'])
if env.get('SECURED') == '1':
-- mediator_rich_test_env.PrependUnique(LIBS = ['tinydtls','ocprovision', 'ocpmapi'])
++ mediator_rich_test_env.PrependUnique(LIBS = ['tinydtls','ocprovision', 'ocpmapi', 'timer'])
mediator_rich_test_env.PrependUnique(LIBS = [
- 'coap',
- 'connectivity_abstraction',
- 'oc_logger',
- 'oc_logger_core',
- 'octbstack',
- 'oc',
+ 'ESMediatorRich',
+ 'oc',
+ 'octbstack',
+ 'oc_logger',
- 'oc_logger_core',
- 'connectivity_abstraction',
- 'coap',
- 'ESMediatorRich',
gtest,
gtest_main])
if target_os not in ['windows', 'winrt']:
mediator_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
--
++
mediator_env.PrependUnique(CPPPATH = [
env.get('SRC_DIR') + '/resource/include',
env.get('SRC_DIR') + '/resource/oc_logger/include',
-- env.get('SRC_DIR') + '/resource/csdk/ocmalloc/include',
++ env.get('SRC_DIR') + '/resource/csdk/ocmalloc/include',
env.get('SRC_DIR') + '/resource/csdk/stack/include',
env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include',
env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
env.get('SRC_DIR') + '/service/easy-setup/mediator/richsdk/src',
env.get('SRC_DIR') + '/service/easy-setup/inc'])
- mediator_env.PrependUnique(LIBS = ['coap'])
- mediator_env.AppendUnique(LIBS = ['connectivity_abstraction'])
- mediator_env.AppendUnique(LIBS = ['oc_logger'])
- mediator_env.AppendUnique(LIBS = ['octbstack'])
- mediator_env.AppendUnique(LIBS = ['oc'])
- mediator_env.AppendUnique(LIBS = ['pthread'])
- mediator_env.AppendUnique(LIBS = ['ESMediatorRich'])
-mediator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction', 'coap', 'ESMediatorRich'])
++if env.get('SECURED') == '1':
++ mediator_env.PrependUnique(LIBS = ['tinydtls', 'timer'])
++
++mediator_env.PrependUnique(LIBS = ['ESMediatorRich', 'oc', 'octbstack', 'oc_logger'])
+
if env.get('SECURED') == '1':
mediator_env.PrependUnique(LIBS = ['ocpmapi', 'ocprovision'])