FrameworkListener.cpp revision fa644ffe944c01a9b00f8d7676d58394fabee285
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#include <errno.h>
17#include <string.h>
18
19#define LOG_TAG "FrameworkListener"
20
21#include <cutils/log.h>
22
23#include <sysutils/FrameworkListener.h>
24#include <sysutils/FrameworkCommand.h>
25#include <sysutils/SocketClient.h>
26
27FrameworkListener::FrameworkListener(const char *socketName) :
28                            SocketListener(socketName, true) {
29    mCommands = new FrameworkCommandCollection();
30}
31
32bool FrameworkListener::onDataAvailable(SocketClient *c) {
33    char buffer[101];
34    int len;
35
36    if ((len = read(c->getSocket(), buffer, sizeof(buffer) -1)) < 0) {
37        LOGE("read() failed (%s)", strerror(errno));
38        return errno;
39    } else if (!len) {
40        LOGW("Lost connection to client");
41        return false;
42    }
43
44    int start = 0;
45    int i;
46
47    buffer[len] = '\0';
48
49    for (i = 0; i < len; i++) {
50        if (buffer[i] == '\0') {
51            dispatchCommand(c, buffer + start);
52            start = i + 1;
53        }
54    }
55    return true;
56}
57
58void FrameworkListener::registerCmd(FrameworkCommand *cmd) {
59    mCommands->push_back(cmd);
60}
61
62void FrameworkListener::dispatchCommand(SocketClient *cli, char *cmd) {
63
64    char *cm, *last;
65
66    if (!(cm = strtok_r(cmd, ":", &last))) {
67        cli->sendMsg("BAD_MSG");
68        return;
69    }
70
71    FrameworkCommandCollection::iterator i;
72
73    for (i = mCommands->begin(); i != mCommands->end(); ++i) {
74        FrameworkCommand *c = *i;
75
76        if (!strcmp(cm, c->getCommand())) {
77            if (c->runCommand(cli, cmd)) {
78                LOGW("Handler '%s' error (%s)", c->getCommand(), strerror(errno));
79            }
80            return;
81        }
82    }
83
84    LOGE("No cmd handlers defined for '%s'", cmd);
85    cli->sendMsg("UNKNOWN_CMD");
86    return;
87}
88