xapian-core  1.4.27
progclient.cc
Go to the documentation of this file.
1 
4 /* Copyright 1999,2000,2001 BrightStation PLC
5  * Copyright 2002 Ananova Ltd
6  * Copyright 2003,2004,2005,2006,2007,2010,2011,2014,2019 Olly Betts
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License as
10  * published by the Free Software Foundation; either version 2 of the
11  * License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
21  * USA
22  */
23 
24 #include <config.h>
25 
26 #include "safefcntl.h"
27 
28 #include "progclient.h"
29 #include <xapian/error.h>
30 #include "closefrom.h"
31 #include "debuglog.h"
32 
33 #include <cerrno>
34 #include <string>
35 #include <vector>
36 
37 #include <sys/types.h>
38 #ifndef __WIN32__
39 # include "safesyssocket.h"
40 # include <sys/wait.h>
41 #else
42 # include <cstdio> // For sprintf().
43 # include <io.h>
44 #endif
45 
46 using namespace std;
47 
48 #ifndef __WIN32__
49 
52 static void
53 split_words(const string &text, vector<string> &words, char ws = ' ')
54 {
55  size_t i = 0;
56  if (i < text.length() && text[0] == ws) {
57  i = text.find_first_not_of(ws, i);
58  }
59  while (i < text.length()) {
60  size_t j = text.find_first_of(ws, i);
61  words.push_back(text.substr(i, j - i));
62  i = text.find_first_not_of(ws, j);
63  }
64 }
65 #endif
66 
67 ProgClient::ProgClient(const string &progname, const string &args,
68  double timeout_, bool writable, int flags)
69  : RemoteDatabase(run_program(progname, args, child),
70  timeout_, get_progcontext(progname, args), writable,
71  flags)
72 {
73  LOGCALL_CTOR(DB, "ProgClient", progname | args | timeout_ | writable | flags);
74 }
75 
76 string
77 ProgClient::get_progcontext(const string &progname, const string &args)
78 {
79  LOGCALL_STATIC(DB, string, "ProgClient::get_progcontext", progname | args);
80  RETURN("remote:prog(" + progname + " " + args + ")");
81 }
82 
83 int
84 ProgClient::run_program(const string &progname, const string &args,
85 #ifndef __WIN32__
86  pid_t& child
87 #else
88  HANDLE& child
89 #endif
90  )
91 {
92  LOGCALL_STATIC(DB, int, "ProgClient::run_program", progname | args | Literal("[&child]"));
93 
94 #if defined HAVE_SOCKETPAIR && defined HAVE_FORK
95  /* socketpair() returns two sockets. We keep sv[0] and give
96  * sv[1] to the child process.
97  */
98  int sv[2];
99 
100  // Set the close-on-exec flag. Our child will clear it after we fork() but
101  // before the child exec()s so that there's no window where another thread
102  // in the parent process could fork()+exec() and end up with these fds
103  // still open.
104  if (socketpair(PF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, sv) < 0) {
105  throw Xapian::NetworkError(string("socketpair failed"), get_progcontext(progname, args), errno);
106  }
107 
108  // Do the steps of splitting args into an argv[] array which need to
109  // allocate memory before we call fork() since in a multi-threaded program
110  // (which we might be used in) it's only safe to call async-signal-safe
111  // functions in the child process after fork() until exec, and malloc, etc
112  // aren't async-signal-safe.
113  vector<string> argvec;
114  split_words(args, argvec);
115  const char **new_argv = new const char *[argvec.size() + 2];
116 
117  child = fork();
118 
119  if (child < 0) {
120  delete [] new_argv;
121  throw Xapian::NetworkError(string("fork failed"), get_progcontext(progname, args), errno);
122  }
123 
124  if (child != 0) {
125  // parent
126  delete [] new_argv;
127  // close the child's end of the socket
128  ::close(sv[1]);
129  RETURN(sv[0]);
130  }
131 
132  /* child process:
133  * set up file descriptors and exec program
134  */
135 
136  // Connect pipe to stdin and stdout. If we set the close-on-exec flag
137  // above, we want to ensure that both fds 0 and 1 are the result of a
138  // dup2() call so that their close-on-exec flags are cleared which we
139  // can do with a little care here.
140  int dup_to_first = 0;
141  if (SOCK_CLOEXEC != 0 && sv[1] == 0) {
142  dup_to_first = 1;
143  }
144 
145  dup2(sv[1], dup_to_first);
146 
147  // Make sure we don't hang on to open files which may get deleted but
148  // not have their disk space released until we exit. Do this before
149  // the second dup2() to ensure there's a free file descriptor.
150  closefrom(2);
151 
152  dup2(dup_to_first, dup_to_first ^ 1);
153 
154  // Redirect stderr to /dev/null
155  int stderrfd = open("/dev/null", O_WRONLY);
156  if (stderrfd == -1) {
157  _exit(-1);
158  }
159  if (stderrfd != 2) {
160  // Not sure why it wouldn't be 2, but handle the situation anyway.
161  dup2(stderrfd, 2);
162  ::close(stderrfd);
163  }
164 
165  new_argv[0] = progname.c_str();
166  for (vector<string>::size_type i = 0; i < argvec.size(); ++i) {
167  new_argv[i + 1] = argvec[i].c_str();
168  }
169  new_argv[argvec.size() + 1] = 0;
170  execvp(progname.c_str(), const_cast<char *const *>(new_argv));
171 
172  // if we get here, then execvp failed.
173  /* throwing an exception is a bad idea, since we're
174  * not the original process. */
175  _exit(-1);
176 #ifdef __xlC__
177  // Avoid "missing return statement" warning.
178  return 0;
179 #endif
180 #elif defined __WIN32__
181  static unsigned int pipecount = 0;
182  char pipename[256];
183 #ifdef SNPRINTF
184  SNPRINTF(pipename, sizeof(pipename),
185  "\\\\.\\pipe\\xapian-remote-%lx-%lx-%x",
186  static_cast<unsigned long>(GetCurrentProcessId()),
187  static_cast<unsigned long>(GetCurrentThreadId()), pipecount++);
188  pipename[sizeof(pipename) - 1] = '\0';
189 #else
190  sprintf(pipename, "\\\\.\\pipe\\xapian-remote-%lx-%lx-%x",
191  static_cast<unsigned long>(GetCurrentProcessId()),
192  static_cast<unsigned long>(GetCurrentThreadId()), pipecount++);
193 #endif
194  // Create a pipe so we can read stdout from the child process.
195  HANDLE hPipe = CreateNamedPipe(pipename,
196  PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
197  0,
198  1, 4096, 4096, NMPWAIT_USE_DEFAULT_WAIT,
199  NULL);
200 
201  if (hPipe == INVALID_HANDLE_VALUE) {
202  throw Xapian::NetworkError("CreateNamedPipe failed",
203  get_progcontext(progname, args),
204  -int(GetLastError()));
205  }
206 
207  HANDLE hClient = CreateFile(pipename,
208  GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
209  FILE_FLAG_OVERLAPPED, NULL);
210 
211  if (hClient == INVALID_HANDLE_VALUE) {
212  throw Xapian::NetworkError("CreateFile failed",
213  get_progcontext(progname, args),
214  -int(GetLastError()));
215  }
216 
217  if (!ConnectNamedPipe(hPipe, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) {
218  throw Xapian::NetworkError("ConnectNamedPipe failed",
219  get_progcontext(progname, args),
220  -int(GetLastError()));
221  }
222 
223  // Set the appropriate handles to be inherited by the child process.
224  SetHandleInformation(hClient, HANDLE_FLAG_INHERIT, 1);
225 
226  // Create the child process.
227  PROCESS_INFORMATION procinfo;
228  memset(&procinfo, 0, sizeof(PROCESS_INFORMATION));
229 
230  STARTUPINFO startupinfo;
231  memset(&startupinfo, 0, sizeof(STARTUPINFO));
232  startupinfo.cb = sizeof(STARTUPINFO);
233  startupinfo.hStdError = hClient;
234  startupinfo.hStdOutput = hClient;
235  startupinfo.hStdInput = hClient;
236  startupinfo.dwFlags |= STARTF_USESTDHANDLES;
237 
238  string cmdline{progname};
239  cmdline += ' ';
240  cmdline += args;
241  // For some reason Windows wants a modifiable command line so we
242  // pass `&cmdline[0]` rather than `cmdline.c_str()`.
243  BOOL ok = CreateProcess(progname.c_str(), &cmdline[0], 0, 0, TRUE, 0, 0, 0,
244  &startupinfo, &procinfo);
245  if (!ok) {
246  throw Xapian::NetworkError("CreateProcess failed",
247  get_progcontext(progname, args),
248  -int(GetLastError()));
249  }
250 
251  CloseHandle(hClient);
252  CloseHandle(procinfo.hThread);
253  child = procinfo.hProcess;
254  RETURN(_open_osfhandle(intptr_t(hPipe), O_RDWR|O_BINARY));
255 #endif
256 }
257 
259 {
260  try {
261  // Close the socket and reap the child.
262  do_close();
263  } catch (...) {
264  }
265 #ifndef __WIN32__
266  waitpid(child, 0, 0);
267 #else
268  WaitForSingleObject(child, INFINITE);
269 #endif
270 }
void close()
Close the database.
#define LOGCALL_STATIC(CATEGORY, TYPE, FUNC, PARAMS)
Definition: debuglog.h:491
#define RETURN(A)
Definition: debuglog.h:493
void closefrom(int fd)
Definition: closefrom.cc:89
include <sys/socket.h> with portability workarounds.
#define O_BINARY
Definition: safefcntl.h:81
Implementation of closefrom() function.
WritableDatabase open()
Construct a WritableDatabase object for a new, empty InMemory database.
Definition: dbfactory.h:104
STL namespace.
#define SOCK_CLOEXEC
Definition: safesyssocket.h:83
void do_close()
Close the socket.
~ProgClient()
Destructor.
Definition: progclient.cc:258
Hierarchy of classes which Xapian can throw as exceptions.
Definition: pretty.h:45
ProgClient(const ProgClient &)
Don&#39;t allow copying.
pid_t child
Process id of the child process.
Definition: progclient.h:43
static void split_words(const string &text, vector< string > &words, char ws=' ')
Split a string into a vector of strings, using a given separator character (default space) ...
Definition: progclient.cc:53
static std::string get_progcontext(const std::string &progname, const std::string &args)
Generate context string for Xapian::Error exception objects.
Definition: progclient.cc:77
RemoteDatabase is the baseclass for remote database implementations.
Implementation of RemoteDatabase using a spawned server.
#define LOGCALL_CTOR(CATEGORY, CLASS, PARAMS)
Definition: debuglog.h:489
Indicates a problem communicating with a remote database.
Definition: error.h:803
include <fcntl.h>, but working around broken platforms.
Debug logging macros.
#define SNPRINTF
Definition: config.h:368
static int run_program(const std::string &progname, const std::string &args, pid_t &child)
Start the child process.
Definition: progclient.cc:84