2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 #include "UnixStream.h"
17 #include <cutils/sockets.h>
24 #include <netinet/in.h>
25 #include <netinet/tcp.h>
29 /* Not all systems define PATH_MAX, those who don't generally don't
30 * have a limit on the maximum path size, so use a value that is
31 * large enough for our very limited needs.
37 UnixStream::UnixStream(size_t bufSize) :
42 UnixStream::UnixStream(int sock, size_t bufSize) :
43 SocketStream(sock, bufSize)
47 /* Initialize a sockaddr_un with the appropriate values corresponding
48 * to a given 'virtual port'. Returns 0 on success, -1 on error.
51 make_unix_path(char *path, size_t pathlen, int port_number)
53 char tmp[PATH_MAX]; // temp directory
56 // First, create user-specific temp directory if needed
57 const char* user = getenv("USER");
60 snprintf(tmp, sizeof(tmp), "/tmp/android-%s", user);
62 ret = ::lstat(tmp, &st);
63 } while (ret < 0 && errno == EINTR);
65 if (ret < 0 && errno == ENOENT) {
67 ret = ::mkdir(tmp, 0766);
68 } while (ret < 0 && errno == EINTR);
70 ERR("Could not create temp directory: %s", tmp);
71 user = NULL; // will fall-back to /tmp
75 user = NULL; // will fallback to /tmp
79 if (user == NULL) { // fallback to /tmp in case of error
80 snprintf(tmp, sizeof(tmp), "/tmp");
83 // Now, initialize it properly
84 snprintf(path, pathlen, "%s/qemu-gles-%d", tmp, port_number);
89 int UnixStream::listen(unsigned short port)
93 if (make_unix_path(path, sizeof(path), port) < 0) {
97 m_sock = socket_local_server(path, ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
98 if (!valid()) return int(ERR_INVALID_SOCKET);
103 SocketStream * UnixStream::accept()
108 struct sockaddr_un addr;
109 socklen_t len = sizeof(addr);
110 clientSock = ::accept(m_sock, (sockaddr *)&addr, &len);
112 if (clientSock < 0 && errno == EINTR) {
118 UnixStream *clientStream = NULL;
120 if (clientSock >= 0) {
121 clientStream = new UnixStream(clientSock, m_bufsize);
126 int UnixStream::connect(unsigned short port)
130 if (make_unix_path(path, sizeof(path), port) < 0)
133 m_sock = socket_local_client(path, ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
134 if (!valid()) return -1;