1/*
2 * Copyright (C) 2008 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 <stdlib.h>
18#include <errno.h>
19#include <fcntl.h>
20#include <string.h>
21
22#include <sys/socket.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25#include <sys/wait.h>
26
27#include <netinet/in.h>
28#include <arpa/inet.h>
29
30#ifdef HAVE_BLUETOOTH
31#include <bluedroid/bluetooth.h>
32#endif
33
34#define LOG_TAG "PanController"
35#include <cutils/log.h>
36
37#include "PanController.h"
38
39#ifdef HAVE_BLUETOOTH
40extern "C" int bt_is_enabled();
41#endif
42
43PanController::PanController() {
44    mPid = 0;
45}
46
47PanController::~PanController() {
48}
49
50int PanController::startPan() {
51    pid_t pid;
52
53#ifdef HAVE_BLUETOOTH
54    if (!bt_is_enabled()) {
55        LOGE("Cannot start PAN services - Bluetooth not running");
56        errno = ENODEV;
57        return -1;
58    }
59#else
60    LOGE("Cannot start PAN services - No Bluetooth support");
61    errno = ENODEV;
62    return -1;
63#endif
64
65    if (mPid) {
66        LOGE("PAN already started");
67        errno = EBUSY;
68        return -1;
69    }
70
71   if ((pid = fork()) < 0) {
72        LOGE("fork failed (%s)", strerror(errno));
73        return -1;
74    }
75
76    if (!pid) {
77        if (execl("/system/bin/pand", "/system/bin/pand", "--nodetach", "--listen",
78                  "--role", "NAP", (char *) NULL)) {
79            LOGE("execl failed (%s)", strerror(errno));
80        }
81        LOGE("Should never get here!");
82        return 0;
83    } else {
84        mPid = pid;
85    }
86    return 0;
87
88}
89
90int PanController::stopPan() {
91    if (mPid == 0) {
92        LOGE("PAN already stopped");
93        return 0;
94    }
95
96    LOGD("Stopping PAN services");
97    kill(mPid, SIGTERM);
98    waitpid(mPid, NULL, 0);
99    mPid = 0;
100    LOGD("PAN services stopped");
101    return 0;
102}
103
104bool PanController::isPanStarted() {
105    return (mPid != 0 ? true : false);
106}
107