1 //===-- RNBSocket.cpp -------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Created by Greg Clayton on 12/12/07.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RNBSocket.h"
15 #include <arpa/inet.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <netdb.h>
19 #include <netinet/in.h>
20 #include <netinet/tcp.h>
21 #include <termios.h>
22 #include "DNBLog.h"
23 #include "DNBError.h"
24 
25 #if defined (__arm__)
26 #include "lockdown.h"
27 #endif
28 
29 /* Once we have a RNBSocket object with a port # specified,
30    this function is called to wait for an incoming connection.
31    This function blocks while waiting for that connection.  */
32 
33 rnb_err_t
34 RNBSocket::Listen (in_port_t listen_port_num)
35 {
36     //DNBLogThreadedIf(LOG_RNB_COMM, "%8u RNBSocket::%s called", (uint32_t)m_timer.ElapsedMicroSeconds(true), __FUNCTION__);
37     // Disconnect without saving errno
38     Disconnect (false);
39 
40     DNBError err;
41     int listen_port = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
42     if (listen_port == -1)
43         err.SetError(errno, DNBError::POSIX);
44 
45     if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
46         err.LogThreaded("::socket ( domain = AF_INET, type = SOCK_STREAM, protocol = IPPROTO_TCP ) => socket = %i", listen_port);
47 
48     if (err.Fail())
49         return rnb_err;
50 
51     // enable local address reuse
52     SetSocketOption (listen_port, SOL_SOCKET, SO_REUSEADDR, 1);
53 
54     struct sockaddr_in sa;
55     ::memset (&sa, 0, sizeof sa);
56     sa.sin_len = sizeof sa;
57     sa.sin_family = AF_INET;
58     sa.sin_port = htons (listen_port_num);
59     sa.sin_addr.s_addr = htonl (INADDR_ANY);
60 
61     int error = ::bind (listen_port, (struct sockaddr *) &sa, sizeof(sa));
62     if (error == -1)
63         err.SetError(errno, DNBError::POSIX);
64 
65     if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
66         err.LogThreaded("::bind ( socket = %i, (struct sockaddr *) &sa, sizeof(sa)) )", listen_port);
67 
68     if (err.Fail())
69     {
70         ClosePort (listen_port, false);
71         return rnb_err;
72     }
73 
74     error = ::listen (listen_port, 1);
75     if (error == -1)
76         err.SetError(errno, DNBError::POSIX);
77 
78     if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
79         err.LogThreaded("::listen ( socket = %i, backlog = 1 )", listen_port);
80 
81     if (err.Fail())
82     {
83         ClosePort (listen_port, false);
84         return rnb_err;
85     }
86 
87     m_conn_port = ::accept (listen_port, NULL, 0);
88     if (m_conn_port == -1)
89         err.SetError(errno, DNBError::POSIX);
90 
91     if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
92         err.LogThreaded("::accept ( socket = %i, address = NULL, address_len = 0 )", listen_port);
93 
94     if (err.Fail())
95     {
96         ClosePort (listen_port, false);
97         return rnb_err;
98     }
99     else
100     {
101         // We are done with the listen port
102         ClosePort (listen_port, false);
103 
104         // Keep our TCP packets coming without any delays.
105         SetSocketOption (m_conn_port, IPPROTO_TCP, TCP_NODELAY, 1);
106     }
107 
108     return rnb_success;
109 }
110 
111 rnb_err_t
112 RNBSocket::Connect (const char *host, uint16_t port)
113 {
114     Disconnect (false);
115 
116     // Create the socket
117     m_conn_port = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
118     if (m_conn_port == -1)
119         return rnb_err;
120 
121     // Enable local address reuse
122     SetSocketOption (m_conn_port, SOL_SOCKET, SO_REUSEADDR, 1);
123 
124     struct sockaddr_in sa;
125     ::memset (&sa, 0, sizeof (sa));
126     sa.sin_family = AF_INET;
127     sa.sin_port = htons (port);
128 
129     if (host == NULL)
130         host = "localhost";
131 
132     int inet_pton_result = ::inet_pton (AF_INET, host, &sa.sin_addr);
133 
134     if (inet_pton_result <= 0)
135     {
136         struct hostent *host_entry = gethostbyname (host);
137         if (host_entry)
138         {
139             std::string host_str (::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list));
140             inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
141             if (inet_pton_result <= 0)
142             {
143                 Disconnect (false);
144                 return rnb_err;
145             }
146         }
147     }
148 
149     if (-1 == ::connect (m_conn_port, (const struct sockaddr *)&sa, sizeof(sa)))
150     {
151         Disconnect (false);
152         return rnb_err;
153     }
154 
155     // Keep our TCP packets coming without any delays.
156     SetSocketOption (m_conn_port, IPPROTO_TCP, TCP_NODELAY, 1);
157     return rnb_success;
158 }
159 
160 #if defined (__arm__)
161 rnb_err_t
162 RNBSocket::ConnectToService()
163 {
164     DNBLog("Connecting to com.apple.%s service...", DEBUGSERVER_PROGRAM_NAME);
165     // Disconnect from any previous connections
166     Disconnect(false);
167 
168     m_conn_port = ::lockdown_checkin (NULL, NULL);
169     if (m_conn_port == -1)
170     {
171         DNBLogThreadedIf(LOG_RNB_COMM, "::lockdown_checkin(NULL, NULL) failed");
172         return rnb_not_connected;
173     }
174     m_conn_port_from_lockdown = true;
175     return rnb_success;
176 }
177 #endif
178 
179 rnb_err_t
180 RNBSocket::OpenFile (const char *path)
181 {
182     DNBError err;
183     m_conn_port = open (path, O_RDWR);
184     if (m_conn_port == -1)
185     {
186         err.SetError(errno, DNBError::POSIX);
187         err.LogThreaded ("can't open file '%s'", path);
188         return rnb_not_connected;
189     }
190     else
191     {
192         struct termios stdin_termios;
193 
194         if (::tcgetattr (m_conn_port, &stdin_termios) == 0)
195         {
196             stdin_termios.c_lflag &= ~ECHO;     // Turn off echoing
197             stdin_termios.c_lflag &= ~ICANON;   // Get one char at a time
198             ::tcsetattr (m_conn_port, TCSANOW, &stdin_termios);
199         }
200     }
201     return rnb_success;
202 }
203 
204 int
205 RNBSocket::SetSocketOption(int fd, int level, int option_name, int option_value)
206 {
207     return ::setsockopt(fd, level, option_name, &option_value, sizeof(option_value));
208 }
209 
210 rnb_err_t
211 RNBSocket::Disconnect (bool save_errno)
212 {
213     if (m_conn_port_from_lockdown)
214         m_conn_port_from_lockdown = false;
215     return ClosePort (m_conn_port, save_errno);
216 }
217 
218 
219 rnb_err_t
220 RNBSocket::Read (std::string &p)
221 {
222     char buf[1024];
223     p.clear();
224 
225     // Note that BUF is on the stack so we must be careful to keep any
226     // writes to BUF from overflowing or we'll have security issues.
227 
228     if (m_conn_port == -1)
229         return rnb_err;
230 
231     //DNBLogThreadedIf(LOG_RNB_COMM, "%8u RNBSocket::%s calling read()", (uint32_t)m_timer.ElapsedMicroSeconds(true), __FUNCTION__);
232     DNBError err;
233     int bytesread = read (m_conn_port, buf, sizeof (buf));
234     if (bytesread <= 0)
235         err.SetError(errno, DNBError::POSIX);
236     else
237         p.append(buf, bytesread);
238 
239     if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
240         err.LogThreaded("::read ( %i, %p, %zu ) => %i", m_conn_port, buf, sizeof (buf), bytesread);
241 
242     // Our port went away - we have to mark this so IsConnected will return the truth.
243     if (bytesread == 0)
244     {
245         m_conn_port = -1;
246         return rnb_not_connected;
247     }
248     else if (bytesread == -1)
249     {
250         m_conn_port = -1;
251         return rnb_err;
252     }
253     // Strip spaces from the end of the buffer
254     while (!p.empty() && isspace (p[p.size() - 1]))
255         p.erase (p.size () - 1);
256 
257     // Most data in the debugserver packets valid printable characters...
258     DNBLogThreadedIf(LOG_RNB_COMM, "read: %s", p.c_str());
259     return rnb_success;
260 }
261 
262 rnb_err_t
263 RNBSocket::Write (const void *buffer, size_t length)
264 {
265     if (m_conn_port == -1)
266         return rnb_err;
267 
268     DNBError err;
269     int bytessent = send (m_conn_port, buffer, length, 0);
270     if (bytessent < 0)
271         err.SetError(errno, DNBError::POSIX);
272 
273     if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
274         err.LogThreaded("::send ( socket = %i, buffer = %p, length = %zu, flags = 0 ) => %i", m_conn_port, buffer, length, bytessent);
275 
276     if (bytessent < 0)
277         return rnb_err;
278 
279     if (bytessent != length)
280         return rnb_err;
281 
282     DNBLogThreadedIf(LOG_RNB_PACKETS, "putpkt: %*s", length, (char *)buffer);   // All data is string based in debugserver, so this is safe
283     DNBLogThreadedIf(LOG_RNB_COMM, "sent: %*s", length, (char *)buffer);
284 
285     return rnb_success;
286 }
287 
288 
289 rnb_err_t
290 RNBSocket::ClosePort (int& fd, bool save_errno)
291 {
292     int close_err = 0;
293     if (fd > 0)
294     {
295         errno = 0;
296         close_err = close (fd);
297         fd = -1;
298     }
299     return close_err != 0 ? rnb_err : rnb_success;
300 }
301 
302 
303