• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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> & args)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     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     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     bool sharingModeMatchRequired = request.isSharingModeMatchRequired();
115     aaudio_sharing_mode_t sharingMode = configurationInput.getSharingMode();
116 
117     // Enforce limit on client processes.
118     AttributionSourceState attributionSource = request.getAttributionSource();
119     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         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         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     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     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     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     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     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     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     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 periodNanoseconds,int32_t * _aidl_return)257 Status AAudioService::registerAudioThread(int32_t streamHandle, int32_t clientThreadId, int64_t periodNanoseconds,
258                                           int32_t *_aidl_return) {
259     static_assert(std::is_same_v<aaudio_result_t, std::decay_t<typeof(*_aidl_return)>>);
260 
261     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     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     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 
isCallerInService()283 bool AAudioService::isCallerInService() {
284     pid_t clientPid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mAudioClient.attributionSource.pid));
285     uid_t clientUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mAudioClient.attributionSource.uid));
286     return clientPid == IPCThreadState::self()->getCallingPid() &&
287         clientUid == IPCThreadState::self()->getCallingUid();
288 }
289 
closeStream(sp<AAudioServiceStreamBase> serviceStream)290 aaudio_result_t AAudioService::closeStream(sp<AAudioServiceStreamBase> serviceStream) {
291     // This is protected by a lock in AAudioClientTracker.
292     // It is safe to unregister the same stream twice.
293     pid_t pid = serviceStream->getOwnerProcessId();
294     AAudioClientTracker::getInstance().unregisterClientStream(pid, serviceStream);
295     // This is protected by a lock in mStreamTracker.
296     // It is safe to remove the same stream twice.
297     mStreamTracker.removeStreamByHandle(serviceStream->getHandle());
298 
299     return serviceStream->close();
300 }
301 
convertHandleToServiceStream(aaudio_handle_t streamHandle)302 sp<AAudioServiceStreamBase> AAudioService::convertHandleToServiceStream(
303         aaudio_handle_t streamHandle) {
304     sp<AAudioServiceStreamBase> serviceStream = mStreamTracker.getStreamByHandle(
305             streamHandle);
306     if (serviceStream.get() != nullptr) {
307         // Only allow owner or the aaudio service to access the stream.
308         const uid_t callingUserId = IPCThreadState::self()->getCallingUid();
309         const uid_t ownerUserId = serviceStream->getOwnerUserId();
310         const uid_t clientUid = VALUE_OR_FATAL(
311             aidl2legacy_int32_t_uid_t(mAudioClient.attributionSource.uid));
312         bool callerOwnsIt = callingUserId == ownerUserId;
313         bool serverCalling = callingUserId == clientUid;
314         bool serverOwnsIt = ownerUserId == clientUid;
315         bool allowed = callerOwnsIt || serverCalling || serverOwnsIt;
316         if (!allowed) {
317             ALOGE("AAudioService: calling uid %d cannot access stream 0x%08X owned by %d",
318                   callingUserId, streamHandle, ownerUserId);
319             serviceStream.clear();
320         }
321     }
322     return serviceStream;
323 }
324 
startClient(aaudio_handle_t streamHandle,const android::AudioClient & client,const audio_attributes_t * attr,audio_port_handle_t * clientHandle)325 aaudio_result_t AAudioService::startClient(aaudio_handle_t streamHandle,
326                                            const android::AudioClient& client,
327                                            const audio_attributes_t *attr,
328                                            audio_port_handle_t *clientHandle) {
329     sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
330     if (serviceStream.get() == nullptr) {
331         ALOGW("%s(), invalid streamHandle = 0x%0x", __func__, streamHandle);
332         return AAUDIO_ERROR_INVALID_HANDLE;
333     }
334     return serviceStream->startClient(client, attr, clientHandle);
335 }
336 
stopClient(aaudio_handle_t streamHandle,audio_port_handle_t portHandle)337 aaudio_result_t AAudioService::stopClient(aaudio_handle_t streamHandle,
338                                           audio_port_handle_t portHandle) {
339     sp<AAudioServiceStreamBase> serviceStream = convertHandleToServiceStream(streamHandle);
340     if (serviceStream.get() == nullptr) {
341         ALOGW("%s(), invalid streamHandle = 0x%0x", __func__, streamHandle);
342         return AAUDIO_ERROR_INVALID_HANDLE;
343     }
344     return serviceStream->stopClient(portHandle);
345 }
346 
347 // This is only called internally when AudioFlinger wants to tear down a stream.
348 // So we do not have to check permissions.
disconnectStreamByPortHandle(audio_port_handle_t portHandle)349 aaudio_result_t AAudioService::disconnectStreamByPortHandle(audio_port_handle_t portHandle) {
350     ALOGD("%s(%d) called", __func__, portHandle);
351     sp<AAudioServiceStreamBase> serviceStream =
352             mStreamTracker.findStreamByPortHandle(portHandle);
353     if (serviceStream.get() == nullptr) {
354         ALOGE("%s(), could not find stream with portHandle = %d", __func__, portHandle);
355         return AAUDIO_ERROR_INVALID_HANDLE;
356     }
357     // This is protected by a lock and will just return if already stopped.
358     aaudio_result_t result = serviceStream->stop();
359     serviceStream->disconnect();
360     return result;
361 }
362