1 /*
2  * Copyright (C) 2016 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 #define LOG_TAG "AAudioService"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20 
21 #include <iomanip>
22 #include <iostream>
23 #include <sstream>
24 
25 #include <android/content/AttributionSourceState.h>
26 #include <aaudio/AAudio.h>
27 #include <media/AidlConversion.h>
28 #include <mediautils/ServiceUtilities.h>
29 #include <utils/String16.h>
30 
31 #include "binding/AAudioServiceMessage.h"
32 #include "AAudioClientTracker.h"
33 #include "AAudioEndpointManager.h"
34 #include "AAudioService.h"
35 #include "AAudioServiceStreamMMAP.h"
36 #include "AAudioServiceStreamShared.h"
37 
38 using namespace android;
39 using namespace aaudio;
40 
41 #define MAX_STREAMS_PER_PROCESS   8
42 #define AIDL_RETURN(x) { *_aidl_return = (x); return Status::ok(); }
43 
44 #define VALUE_OR_RETURN_ILLEGAL_ARG_STATUS(x) \
45     ({ auto _tmp = (x); \
46        if (!_tmp.ok()) AIDL_RETURN(AAUDIO_ERROR_ILLEGAL_ARGUMENT); \
47        std::move(_tmp.value()); })
48 
49 using android::AAudioService;
50 using android::content::AttributionSourceState;
51 using binder::Status;
52 
AAudioService()53 android::AAudioService::AAudioService()
54     : BnAAudioService(),
55       mAdapter(this) {
56     // TODO consider using geteuid()
57     // TODO b/182392769: use attribution source util
58     mAudioClient.attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid()));
59     mAudioClient.attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(getpid()));
60     mAudioClient.attributionSource.packageName = std::nullopt;
61     mAudioClient.attributionSource.attributionTag = std::nullopt;
62     AAudioClientTracker::getInstance().setAAudioService(this);
63 }
64 
dump(int fd,const Vector<String16> &)65 status_t AAudioService::dump(int fd, const Vector<String16>& /*args*/) {
66     std::string result;
67 
68     if (!dumpAllowed()) {
69         std::stringstream ss;
70         ss << "Permission Denial: can't dump AAudioService from pid="
71                 << IPCThreadState::self()->getCallingPid() << ", uid="
72                 << IPCThreadState::self()->getCallingUid() << "\n";
73         result = ss.str();
74         ALOGW("%s", result.c_str());
75     } else {
76         result = "------------ AAudio Service ------------\n"
77                  + mStreamTracker.dump()
78                  + AAudioClientTracker::getInstance().dump()
79                  + AAudioEndpointManager::getInstance().dump();
80     }
81     (void)write(fd, result.c_str(), result.size());
82     return NO_ERROR;
83 }
84 
registerClient(const sp<IAAudioClient> & client)85 Status AAudioService::registerClient(const sp<IAAudioClient> &client) {
86     const pid_t pid = IPCThreadState::self()->getCallingPid();
87     AAudioClientTracker::getInstance().registerClient(pid, client);
88     return Status::ok();
89 }
90 
91 Status
openStream(const StreamRequest & _request,StreamParameters * _paramsOut,int32_t * _aidl_return)92 AAudioService::openStream(const StreamRequest &_request, StreamParameters* _paramsOut,
93                           int32_t *_aidl_return) {
94     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
95 
96     // Create wrapper objects for simple usage of the parcelables.
97     const AAudioStreamRequest request(_request);
98     AAudioStreamConfiguration paramsOut;
99 
100     // A lock in is used to order the opening of endpoints when an
101     // EXCLUSIVE endpoint is stolen. We want the order to be:
102     // 1) Thread A opens exclusive MMAP endpoint
103     // 2) Thread B wants to open an exclusive MMAP endpoint so it steals the one from A
104     //    under this lock.
105     // 3) Thread B opens a shared MMAP endpoint.
106     // 4) Thread A can then get the lock and also open a shared stream.
107     // Without the lock. Thread A might sneak in and reallocate an exclusive stream
108     // before B can open the shared stream.
109     const std::unique_lock<std::recursive_mutex> lock(mOpenLock);
110 
111     aaudio_result_t result = AAUDIO_OK;
112     sp<AAudioServiceStreamBase> serviceStream;
113     const AAudioStreamConfiguration &configurationInput = request.getConstantConfiguration();
114     const bool sharingModeMatchRequired = request.isSharingModeMatchRequired();
115     const aaudio_sharing_mode_t sharingMode = configurationInput.getSharingMode();
116 
117     // Enforce limit on client processes.
118     AttributionSourceState attributionSource = request.getAttributionSource();
119     const pid_t pid = IPCThreadState::self()->getCallingPid();
120     attributionSource.pid = VALUE_OR_RETURN_ILLEGAL_ARG_STATUS(
121         legacy2aidl_pid_t_int32_t(pid));
122     attributionSource.uid = VALUE_OR_RETURN_ILLEGAL_ARG_STATUS(
123         legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
124     attributionSource.token = sp<BBinder>::make();
125     if (attributionSource.pid != mAudioClient.attributionSource.pid) {
126         const int32_t count = AAudioClientTracker::getInstance().getStreamCount(pid);
127         if (count >= MAX_STREAMS_PER_PROCESS) {
128             ALOGE("openStream(): exceeded max streams per process %d >= %d",
129                   count,  MAX_STREAMS_PER_PROCESS);
130             AIDL_RETURN(AAUDIO_ERROR_UNAVAILABLE);
131         }
132     }
133 
134     if (sharingMode != AAUDIO_SHARING_MODE_EXCLUSIVE && sharingMode != AAUDIO_SHARING_MODE_SHARED) {
135         ALOGE("openStream(): unrecognized sharing mode = %d", sharingMode);
136         AIDL_RETURN(AAUDIO_ERROR_ILLEGAL_ARGUMENT);
137     }
138 
139     if (sharingMode == AAUDIO_SHARING_MODE_EXCLUSIVE
140         && AAudioClientTracker::getInstance().isExclusiveEnabled(pid)) {
141         // only trust audioserver for in service indication
142         bool inService = false;
143         if (isCallerInService()) {
144             inService = request.isInService();
145         }
146         serviceStream = new AAudioServiceStreamMMAP(*this, inService);
147         result = serviceStream->open(request);
148         if (result != AAUDIO_OK) {
149             // Clear it so we can possibly fall back to using a shared stream.
150             ALOGW("openStream(), could not open in EXCLUSIVE mode");
151             serviceStream.clear();
152         }
153     }
154 
155     // Try SHARED if SHARED requested or if EXCLUSIVE failed.
156     if (sharingMode == AAUDIO_SHARING_MODE_SHARED) {
157         serviceStream =  new AAudioServiceStreamShared(*this);
158         result = serviceStream->open(request);
159     } else if (serviceStream.get() == nullptr && !sharingModeMatchRequired) {
160         aaudio::AAudioStreamRequest modifiedRequest = request;
161         // Overwrite the original EXCLUSIVE mode with SHARED.
162         modifiedRequest.getConfiguration().setSharingMode(AAUDIO_SHARING_MODE_SHARED);
163         serviceStream =  new AAudioServiceStreamShared(*this);
164         result = serviceStream->open(modifiedRequest);
165     }
166 
167     if (result != AAUDIO_OK) {
168         serviceStream.clear();
169         AIDL_RETURN(result);
170     } else {
171         const aaudio_handle_t handle = mStreamTracker.addStreamForHandle(serviceStream.get());
172         serviceStream->setHandle(handle);
173         AAudioClientTracker::getInstance().registerClientStream(pid, serviceStream);
174         paramsOut.copyFrom(*serviceStream);
175         *_paramsOut = std::move(paramsOut).parcelable();
176         // Log open in MediaMetrics after we have the handle because we need the handle to
177         // create the metrics ID.
178         serviceStream->logOpen(handle);
179         ALOGV("%s(): return handle = 0x%08X", __func__, handle);
180         AIDL_RETURN(handle);
181     }
182 }
183 
closeStream(int32_t streamHandle,int32_t * _aidl_return)184 Status AAudioService::closeStream(int32_t streamHandle, int32_t *_aidl_return) {
185     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
186 
187     // Check permission and ownership first.
188     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
189     if (serviceStream.get() == nullptr) {
190         ALOGE("closeStream(0x%0x), illegal stream handle", streamHandle);
191         AIDL_RETURN(AAUDIO_ERROR_INVALID_HANDLE);
192     }
193     AIDL_RETURN(closeStream(serviceStream));
194 }
195 
getStreamDescription(int32_t streamHandle,Endpoint * endpoint,int32_t * _aidl_return)196 Status AAudioService::getStreamDescription(int32_t streamHandle, Endpoint* endpoint,
197                                            int32_t *_aidl_return) {
198     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
199 
200     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
201     if (serviceStream.get() == nullptr) {
202         ALOGE("getStreamDescription(), illegal stream handle = 0x%0x", streamHandle);
203         AIDL_RETURN(AAUDIO_ERROR_INVALID_HANDLE);
204     }
205     AudioEndpointParcelable endpointParcelable;
206     const aaudio_result_t result = serviceStream->getDescription(endpointParcelable);
207     if (result == AAUDIO_OK) {
208         *endpoint = std::move(endpointParcelable).parcelable();
209     }
210     AIDL_RETURN(result);
211 }
212 
startStream(int32_t streamHandle,int32_t * _aidl_return)213 Status AAudioService::startStream(int32_t streamHandle, int32_t *_aidl_return) {
214     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
215 
216     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
217     if (serviceStream.get() == nullptr) {
218         ALOGW("%s(), invalid streamHandle = 0x%0x", __func__, streamHandle);
219         AIDL_RETURN(AAUDIO_ERROR_INVALID_HANDLE);
220     }
221     AIDL_RETURN(serviceStream->start());
222 }
223 
pauseStream(int32_t streamHandle,int32_t * _aidl_return)224 Status AAudioService::pauseStream(int32_t streamHandle, int32_t *_aidl_return) {
225     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
226 
227     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
228     if (serviceStream.get() == nullptr) {
229         ALOGW("%s(), invalid streamHandle = 0x%0x", __func__, streamHandle);
230         AIDL_RETURN(AAUDIO_ERROR_INVALID_HANDLE);
231     }
232     AIDL_RETURN(serviceStream->pause());
233 }
234 
stopStream(int32_t streamHandle,int32_t * _aidl_return)235 Status AAudioService::stopStream(int32_t streamHandle, int32_t *_aidl_return) {
236     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
237 
238     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
239     if (serviceStream.get() == nullptr) {
240         ALOGW("%s(), invalid streamHandle = 0x%0x", __func__, streamHandle);
241         AIDL_RETURN(AAUDIO_ERROR_INVALID_HANDLE);
242     }
243     AIDL_RETURN(serviceStream->stop());
244 }
245 
flushStream(int32_t streamHandle,int32_t * _aidl_return)246 Status AAudioService::flushStream(int32_t streamHandle, int32_t *_aidl_return) {
247     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
248 
249     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
250     if (serviceStream.get() == nullptr) {
251         ALOGW("%s(), invalid streamHandle = 0x%0x", __func__, streamHandle);
252         AIDL_RETURN(AAUDIO_ERROR_INVALID_HANDLE);
253     }
254     AIDL_RETURN(serviceStream->flush());
255 }
256 
registerAudioThread(int32_t streamHandle,int32_t clientThreadId,int64_t,int32_t * _aidl_return)257 Status AAudioService::registerAudioThread(int32_t streamHandle, int32_t clientThreadId,
258                                           int64_t /*periodNanoseconds*/, int32_t *_aidl_return) {
259     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
260 
261     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
262     if (serviceStream.get() == nullptr) {
263         ALOGW("%s(), invalid streamHandle = 0x%0x", __func__, streamHandle);
264         AIDL_RETURN(AAUDIO_ERROR_INVALID_HANDLE);
265     }
266     const int32_t priority = isCallerInService()
267         ? kRealTimeAudioPriorityService : kRealTimeAudioPriorityClient;
268     AIDL_RETURN(serviceStream->registerAudioThread(clientThreadId, priority));
269 }
270 
unregisterAudioThread(int32_t streamHandle,int32_t clientThreadId,int32_t * _aidl_return)271 Status AAudioService::unregisterAudioThread(int32_t streamHandle, int32_t clientThreadId,
272                                             int32_t *_aidl_return) {
273     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
274 
275     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
276     if (serviceStream.get() == nullptr) {
277         ALOGW("%s(), invalid streamHandle = 0x%0x", __func__, streamHandle);
278         AIDL_RETURN(AAUDIO_ERROR_INVALID_HANDLE);
279     }
280     AIDL_RETURN(serviceStream->unregisterAudioThread(clientThreadId));
281 }
282 
exitStandby(int32_t streamHandle,Endpoint * endpoint,int32_t * _aidl_return)283 Status AAudioService::exitStandby(int32_t streamHandle, Endpoint* endpoint, int32_t *_aidl_return) {
284     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
285 
286     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
287     if (serviceStream.get() == nullptr) {
288         ALOGE("getStreamDescription(), illegal stream handle = 0x%0x", streamHandle);
289         AIDL_RETURN(AAUDIO_ERROR_INVALID_HANDLE);
290     }
291     AudioEndpointParcelable endpointParcelable;
292     const aaudio_result_t result = serviceStream->exitStandby(&endpointParcelable);
293     if (result == AAUDIO_OK) {
294         *endpoint = std::move(endpointParcelable).parcelable();
295     }
296     AIDL_RETURN(result);
297 }
298 
isCallerInService()299 bool AAudioService::isCallerInService() {
300     const pid_t clientPid = VALUE_OR_FATAL(
301             aidl2legacy_int32_t_pid_t(mAudioClient.attributionSource.pid));
302     const uid_t clientUid = VALUE_OR_FATAL(
303             aidl2legacy_int32_t_uid_t(mAudioClient.attributionSource.uid));
304     return clientPid == IPCThreadState::self()->getCallingPid() &&
305         clientUid == IPCThreadState::self()->getCallingUid();
306 }
307 
closeStream(const sp<AAudioServiceStreamBase> & serviceStream)308 aaudio_result_t AAudioService::closeStream(const sp<AAudioServiceStreamBase>& serviceStream) {
309     // This is protected by a lock in AAudioClientTracker.
310     // It is safe to unregister the same stream twice.
311     const pid_t pid = serviceStream->getOwnerProcessId();
312     AAudioClientTracker::getInstance().unregisterClientStream(pid, serviceStream);
313     // This is protected by a lock in mStreamTracker.
314     // It is safe to remove the same stream twice.
315     mStreamTracker.removeStreamByHandle(serviceStream->getHandle());
316 
317     return serviceStream->close();
318 }
319 
convertHandleToServiceStream(aaudio_handle_t streamHandle)320 sp<AAudioServiceStreamBase> AAudioService::convertHandleToServiceStream(
321         aaudio_handle_t streamHandle) {
322     sp<AAudioServiceStreamBase> serviceStream = mStreamTracker.getStreamByHandle(
323             streamHandle);
324     if (serviceStream.get() != nullptr) {
325         // Only allow owner or the aaudio service to access the stream.
326         const uid_t callingUserId = IPCThreadState::self()->getCallingUid();
327         const uid_t ownerUserId = serviceStream->getOwnerUserId();
328         const uid_t clientUid = VALUE_OR_FATAL(
329             aidl2legacy_int32_t_uid_t(mAudioClient.attributionSource.uid));
330         const bool callerOwnsIt = callingUserId == ownerUserId;
331         const bool serverCalling = callingUserId == clientUid;
332         const bool serverOwnsIt = ownerUserId == clientUid;
333         const bool allowed = callerOwnsIt || serverCalling || serverOwnsIt;
334         if (!allowed) {
335             ALOGE("AAudioService: calling uid %d cannot access stream 0x%08X owned by %d",
336                   callingUserId, streamHandle, ownerUserId);
337             serviceStream.clear();
338         }
339     }
340     return serviceStream;
341 }
342 
startClient(aaudio_handle_t streamHandle,const android::AudioClient & client,const audio_attributes_t * attr,audio_port_handle_t * clientHandle)343 aaudio_result_t AAudioService::startClient(aaudio_handle_t streamHandle,
344                                            const android::AudioClient& client,
345                                            const audio_attributes_t *attr,
346                                            audio_port_handle_t *clientHandle) {
347     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
348     if (serviceStream.get() == nullptr) {
349         ALOGW("%s(), invalid streamHandle = 0x%0x", __func__, streamHandle);
350         return AAUDIO_ERROR_INVALID_HANDLE;
351     }
352     return serviceStream->startClient(client, attr, clientHandle);
353 }
354 
stopClient(aaudio_handle_t streamHandle,audio_port_handle_t portHandle)355 aaudio_result_t AAudioService::stopClient(aaudio_handle_t streamHandle,
356                                           audio_port_handle_t portHandle) {
357     const sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
358     if (serviceStream.get() == nullptr) {
359         ALOGW("%s(), invalid streamHandle = 0x%0x", __func__, streamHandle);
360         return AAUDIO_ERROR_INVALID_HANDLE;
361     }
362     return serviceStream->stopClient(portHandle);
363 }
364 
365 // This is only called internally when AudioFlinger wants to tear down a stream.
366 // So we do not have to check permissions.
disconnectStreamByPortHandle(audio_port_handle_t portHandle)367 aaudio_result_t AAudioService::disconnectStreamByPortHandle(audio_port_handle_t portHandle) {
368     ALOGD("%s(%d) called", __func__, portHandle);
369     const sp<AAudioServiceStreamBase> serviceStream =
370             mStreamTracker.findStreamByPortHandle(portHandle);
371     if (serviceStream.get() == nullptr) {
372         ALOGE("%s(), could not find stream with portHandle = %d", __func__, portHandle);
373         return AAUDIO_ERROR_INVALID_HANDLE;
374     }
375     // This is protected by a lock and will just return if already stopped.
376     const aaudio_result_t result = serviceStream->stop();
377     serviceStream->disconnect();
378     return result;
379 }
380