1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "buffet/flouride_socket_bluetooth_client.h"
18 
19 #include <sys/socket.h>
20 #include <sys/un.h>
21 
22 #include <brillo/streams/file_stream.h>
23 
24 namespace buffet {
25 
26 const char kFlourideSocketPath[] = "/dev/socket/bluetooth";
27 
CreateInstance()28 std::unique_ptr<BluetoothClient> BluetoothClient::CreateInstance() {
29   return std::unique_ptr<BluetoothClient>{new FlourideSocketBluetoothClient};
30 }
31 
FlourideSocketBluetoothClient()32 FlourideSocketBluetoothClient::FlourideSocketBluetoothClient() {}
33 
~FlourideSocketBluetoothClient()34 FlourideSocketBluetoothClient::~FlourideSocketBluetoothClient() {}
35 
36 // TODO(rginda): Call this from somewhere.
OpenSocket()37 bool FlourideSocketBluetoothClient::OpenSocket() {
38   LOG(INFO) << "Opening: " << kFlourideSocketPath;
39 
40   int socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
41   if (socket_fd < 0) {
42     PLOG(ERROR) << "Failed to create domain socket: " << kFlourideSocketPath;
43     return false;
44   }
45 
46   sockaddr_un addr{AF_UNIX};
47   static_assert(sizeof(kFlourideSocketPath) <= sizeof(addr.sun_path),
48                 "kFlourideSocketPath too long");
49   strncpy(addr.sun_path, kFlourideSocketPath, sizeof(addr.sun_path));
50   if (connect(socket_fd, reinterpret_cast<sockaddr *>(&addr),
51               sizeof(sockaddr_un))) {
52     PLOG(ERROR) << "Failed to connect to domain socket: "
53                 << kFlourideSocketPath;
54     close(socket_fd);
55     return false;
56   }
57 
58   stream_ = brillo::FileStream::FromFileDescriptor(socket_fd, true, nullptr);
59   return true;
60 }
61 
62 }  // namespace buffet
63