servicemanager: restrict service name characters

This is in order to, in the future, potentially have special policy
like:
vendor$vendor_service u:object_r:...:s0
universal$hal_foo_service u:object_r:...:s0

Currently, there are no special characters that could be used for this
purpose.

How safe is this? In all context files in our internal tree, only the
following characters are used in service names:
-._12aAbBcCdDeEfFgGhHiIjkKlmMnNoOpPqQrsStTuUvwWxyz

'.' appears everywhere to mean '\.'.

Test: servicemanager_test
Bug: 136027762
Change-Id: Idd6698a68bbbe825dd5a25d92baf81fae473ea2a
diff --git a/cmds/servicemanager/ServiceManager.cpp b/cmds/servicemanager/ServiceManager.cpp
index b88b67d..6cfcf40 100644
--- a/cmds/servicemanager/ServiceManager.cpp
+++ b/cmds/servicemanager/ServiceManager.cpp
@@ -63,6 +63,21 @@
     return Status::ok();
 }
 
+bool isValidServiceName(const std::string& name) {
+    if (name.size() == 0) return false;
+    if (name.size() > 127) return false;
+
+    for (char c : name) {
+        if (c == '_' || c == '-' || c == '.') continue;
+        if (c >= 'a' && c <= 'z') continue;
+        if (c >= 'A' && c <= 'Z') continue;
+        if (c >= '0' && c <= '9') continue;
+        return false;
+    }
+
+    return true;
+}
+
 Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
     auto ctx = mAccess->getCallingContext(name);
 
@@ -79,8 +94,8 @@
         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
     }
 
-    // match legacy rules
-    if (name.size() == 0 || name.size() > 127) {
+    if (!isValidServiceName(name)) {
+        LOG(ERROR) << "Invalid service name: " << name;
         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
     }