tesseract  4.00.00dev
svutil.cpp
Go to the documentation of this file.
1 // File: svutil.cpp
3 // Description: ScrollView Utilities
4 // Author: Joern Wanke
5 // Created: Thu Nov 29 2007
6 //
7 // (C) Copyright 2007, Google Inc.
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
19 //
20 // SVUtil contains the SVSync and SVNetwork classes, which are used for
21 // thread/process creation & synchronization and network connection.
22 
23 #include <stdio.h>
24 #ifdef _WIN32
25 #include <windows.h>
26 struct addrinfo {
27  struct sockaddr* ai_addr;
28  int ai_addrlen;
29  int ai_family;
30  int ai_socktype;
31  int ai_protocol;
32 };
33 #else
34 #include <arpa/inet.h>
35 #include <netdb.h>
36 #include <netinet/in.h>
37 #include <pthread.h>
38 #include <semaphore.h>
39 #include <signal.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/select.h>
43 #include <sys/socket.h>
44 #ifdef __linux__
45 #include <sys/prctl.h>
46 #endif
47 #include <unistd.h>
48 #endif
49 
50 #include <cstdlib>
51 #include <cstring>
52 #include <iostream>
53 #include <string>
54 
55 // Include automatically generated configuration file if running autoconf.
56 #ifdef HAVE_CONFIG_H
57 #include "config_auto.h"
58 #endif
59 
60 #include "svutil.h"
61 
63 #ifdef _WIN32
64  mutex_ = CreateMutex(0, FALSE, 0);
65 #else
66  pthread_mutex_init(&mutex_, NULL);
67 #endif
68 }
69 
70 void SVMutex::Lock() {
71 #ifdef _WIN32
72  WaitForSingleObject(mutex_, INFINITE);
73 #else
74  pthread_mutex_lock(&mutex_);
75 #endif
76 }
77 
79 #ifdef _WIN32
80  ReleaseMutex(mutex_);
81 #else
82  pthread_mutex_unlock(&mutex_);
83 #endif
84 }
85 
86 // Create new thread.
87 void SVSync::StartThread(void* (*func)(void*), void* arg) {
88 #ifdef _WIN32
89  LPTHREAD_START_ROUTINE f = (LPTHREAD_START_ROUTINE)func;
90  DWORD threadid;
91  HANDLE newthread = CreateThread(NULL, // default security attributes
92  0, // use default stack size
93  f, // thread function
94  arg, // argument to thread function
95  0, // use default creation flags
96  &threadid); // returns the thread identifier
97 #else
98  pthread_t helper;
99  pthread_attr_t attr;
100  pthread_attr_init(&attr);
101  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
102  pthread_create(&helper, &attr, func, arg);
103 #endif
104 }
105 
106 #ifndef GRAPHICS_DISABLED
107 
108 const int kMaxMsgSize = 4096;
109 
110 // Signals a thread to exit.
112 #ifdef _WIN32
113  // ExitThread(0);
114 #else
115  pthread_exit(0);
116 #endif
117 }
118 
119 // Starts a new process.
120 void SVSync::StartProcess(const char* executable, const char* args) {
121  std::string proc;
122  proc.append(executable);
123  proc.append(" ");
124  proc.append(args);
125  std::cout << "Starting " << proc << std::endl;
126 #ifdef _WIN32
127  STARTUPINFO start_info;
128  PROCESS_INFORMATION proc_info;
129  GetStartupInfo(&start_info);
130  if (!CreateProcess(NULL, const_cast<char*>(proc.c_str()), NULL, NULL, FALSE,
131  CREATE_NO_WINDOW | DETACHED_PROCESS, NULL, NULL,
132  &start_info, &proc_info))
133  return;
134 #else
135  int pid = fork();
136  if (pid != 0) { // The father process returns
137  } else {
138 #ifdef __linux__
139  // Make sure the java process terminates on exit, since its
140  // broken socket detection seems to be useless.
141  prctl(PR_SET_PDEATHSIG, 2, 0, 0, 0);
142 #endif
143  char* mutable_args = strdup(args);
144  int argc = 1;
145  for (int i = 0; mutable_args[i]; ++i) {
146  if (mutable_args[i] == ' ') {
147  ++argc;
148  }
149  }
150  char** argv = new char*[argc + 2];
151  argv[0] = strdup(executable);
152  argv[1] = mutable_args;
153  argc = 2;
154  bool inquote = false;
155  for (int i = 0; mutable_args[i]; ++i) {
156  if (!inquote && mutable_args[i] == ' ') {
157  mutable_args[i] = '\0';
158  argv[argc++] = mutable_args + i + 1;
159  } else if (mutable_args[i] == '"') {
160  inquote = !inquote;
161  mutable_args[i] = ' ';
162  }
163  }
164  argv[argc] = NULL;
165  execvp(executable, argv);
166  free(argv[0]);
167  free(argv[1]);
168  delete[] argv;
169  }
170 #endif
171 }
172 
174 #ifdef _WIN32
175  semaphore_ = CreateSemaphore(0, 0, 10, 0);
176 #elif defined(__APPLE__)
177  char name[50];
178  snprintf(name, sizeof(name), "%ld", random());
179  sem_unlink(name);
180  semaphore_ = sem_open(name, O_CREAT , S_IWUSR, 0);
181  if (semaphore_ == SEM_FAILED) {
182  perror("sem_open");
183  }
184 #else
185  sem_init(&semaphore_, 0, 0);
186 #endif
187 }
188 
190 #ifdef _WIN32
191  ReleaseSemaphore(semaphore_, 1, NULL);
192 #elif defined(__APPLE__)
193  sem_post(semaphore_);
194 #else
195  sem_post(&semaphore_);
196 #endif
197 }
198 
200 #ifdef _WIN32
201  WaitForSingleObject(semaphore_, INFINITE);
202 #elif defined(__APPLE__)
203  sem_wait(semaphore_);
204 #else
205  sem_wait(&semaphore_);
206 #endif
207 }
208 
209 // Place a message in the message buffer (and flush it).
210 void SVNetwork::Send(const char* msg) {
211  mutex_send_.Lock();
212  msg_buffer_out_.append(msg);
213  mutex_send_.Unlock();
214 }
215 
216 // Send the whole buffer.
218  mutex_send_.Lock();
219  while (!msg_buffer_out_.empty()) {
220  int i = send(stream_, msg_buffer_out_.c_str(), msg_buffer_out_.length(), 0);
221  msg_buffer_out_.erase(0, i);
222  }
223  mutex_send_.Unlock();
224 }
225 
226 // Receive a message from the server.
227 // This will always return one line of char* (denoted by \n).
229  char* result = NULL;
230 #if defined(_WIN32) || defined(__CYGWIN__)
231  if (has_content) { result = strtok (NULL, "\n"); }
232 #else
233  if (buffer_ptr_ != NULL) { result = strtok_r(NULL, "\n", &buffer_ptr_); }
234 #endif
235 
236  // This means there is something left in the buffer and we return it.
237  if (result != NULL) { return result;
238  // Otherwise, we read from the stream_.
239  } else {
240  buffer_ptr_ = NULL;
241  has_content = false;
242 
243  // The timeout length is not really important since we are looping anyway
244  // until a new message is delivered.
245  struct timeval tv;
246  tv.tv_sec = 10;
247  tv.tv_usec = 0;
248 
249  // Set the flags to return when the stream_ is ready to be read.
250  fd_set readfds;
251  FD_ZERO(&readfds);
252  FD_SET(stream_, &readfds);
253 
254  int i = select(stream_+1, &readfds, NULL, NULL, &tv);
255 
256  // The stream_ died.
257  if (i == 0) { return NULL; }
258 
259  // Read the message buffer.
260  i = recv(stream_, msg_buffer_in_, kMaxMsgSize, 0);
261 
262  // Server quit (0) or error (-1).
263  if (i <= 0) { return NULL; }
264  msg_buffer_in_[i] = '\0';
265  has_content = true;
266 #ifdef _WIN32
267  return strtok(msg_buffer_in_, "\n");
268 #else
269  // Setup a new string tokenizer.
270  return strtok_r(msg_buffer_in_, "\n", &buffer_ptr_);
271 #endif
272  }
273 }
274 
275 // Close the connection to the server.
277 #ifdef _WIN32
278  closesocket(stream_);
279 #else
280  close(stream_);
281 #endif
282 }
283 
284 
285 // The program to invoke to start ScrollView
286 static const char* ScrollViewProg() {
287 #ifdef _WIN32
288  const char* prog = "java -Xms512m -Xmx1024m";
289 #else
290  const char* prog = "sh";
291 #endif
292  return prog;
293 }
294 
295 
296 // The arguments to the program to invoke to start ScrollView
297 static std::string ScrollViewCommand(std::string scrollview_path) {
298  // The following ugly ifdef is to enable the output of the java runtime
299  // to be sent down a black hole on non-windows to ignore all the
300  // exceptions in piccolo. Ideally piccolo would be debugged to make
301  // this unnecessary.
302  // Also the path has to be separated by ; on windows and : otherwise.
303 #ifdef _WIN32
304  const char* cmd_template = "-Djava.library.path=%s -jar %s/ScrollView.jar";
305 
306 #else
307  const char* cmd_template =
308  "-c \"trap 'kill %%1' 0 1 2 ; java "
309  "-Xms1024m -Xmx2048m -jar %s/ScrollView.jar"
310  " & wait\"";
311 #endif
312  int cmdlen = strlen(cmd_template) + 4*strlen(scrollview_path.c_str()) + 1;
313  char* cmd = new char[cmdlen];
314  const char* sv_path = scrollview_path.c_str();
315  snprintf(cmd, cmdlen, cmd_template, sv_path, sv_path, sv_path, sv_path);
316  std::string command(cmd);
317  delete [] cmd;
318  return command;
319 }
320 
321 
322 // Platform-independent freeaddrinfo()
323 static void FreeAddrInfo(struct addrinfo* addr_info) {
324  #if defined(__linux__)
325  freeaddrinfo(addr_info);
326  #else
327  delete addr_info->ai_addr;
328  delete addr_info;
329  #endif
330 }
331 
332 
333 // Non-linux version of getaddrinfo()
334 #if !defined(__linux__)
335 static int GetAddrInfoNonLinux(const char* hostname, int port,
336  struct addrinfo** addr_info) {
337 // Get the host data depending on the OS.
338  struct sockaddr_in* address;
339  *addr_info = new struct addrinfo;
340  memset(*addr_info, 0, sizeof(struct addrinfo));
341  address = new struct sockaddr_in;
342  memset(address, 0, sizeof(struct sockaddr_in));
343 
344  (*addr_info)->ai_addr = (struct sockaddr*) address;
345  (*addr_info)->ai_addrlen = sizeof(struct sockaddr);
346  (*addr_info)->ai_family = AF_INET;
347  (*addr_info)->ai_socktype = SOCK_STREAM;
348 
349  struct hostent *name;
350 #ifdef _WIN32
351  WSADATA wsaData;
352  WSAStartup(MAKEWORD(1, 1), &wsaData);
353  name = gethostbyname(hostname);
354 #else
355  name = gethostbyname(hostname);
356 #endif
357 
358  if (name == NULL) {
359  FreeAddrInfo(*addr_info);
360  *addr_info = NULL;
361  return -1;
362  }
363 
364  // Fill in the appropriate variables to be able to connect to the server.
365  address->sin_family = name->h_addrtype;
366  memcpy((char *) &address->sin_addr.s_addr,
367  name->h_addr_list[0], name->h_length);
368  address->sin_port = htons(port);
369  return 0;
370 }
371 #endif
372 
373 
374 // Platform independent version of getaddrinfo()
375 // Given a hostname:port, produce an addrinfo struct
376 static int GetAddrInfo(const char* hostname, int port,
377  struct addrinfo** address) {
378 #if defined(__linux__)
379  char port_str[40];
380  snprintf(port_str, 40, "%d", port);
381  return getaddrinfo(hostname, port_str, NULL, address);
382 #else
383  return GetAddrInfoNonLinux(hostname, port, address);
384 #endif
385 }
386 
387 
388 // Set up a connection to a ScrollView on hostname:port.
389 SVNetwork::SVNetwork(const char* hostname, int port) {
390  msg_buffer_in_ = new char[kMaxMsgSize + 1];
391  msg_buffer_in_[0] = '\0';
392 
393  has_content = false;
394  buffer_ptr_ = NULL;
395 
396  struct addrinfo *addr_info = NULL;
397 
398  if (GetAddrInfo(hostname, port, &addr_info) != 0) {
399  std::cerr << "Error resolving name for ScrollView host "
400  << std::string(hostname) << ":" << port << std::endl;
401  }
402 
403  stream_ = socket(addr_info->ai_family, addr_info->ai_socktype,
404  addr_info->ai_protocol);
405 
406  // If server is not there, we will start a new server as local child process.
407  if (connect(stream_, addr_info->ai_addr, addr_info->ai_addrlen) < 0) {
408  const char* scrollview_path = getenv("SCROLLVIEW_PATH");
409  if (scrollview_path == NULL) {
410 #ifdef SCROLLVIEW_PATH
411 #define _STR(a) #a
412 #define _XSTR(a) _STR(a)
413  scrollview_path = _XSTR(SCROLLVIEW_PATH);
414 #undef _XSTR
415 #undef _STR
416 #else
417  scrollview_path = ".";
418 #endif
419  }
420  const char *prog = ScrollViewProg();
421  std::string command = ScrollViewCommand(scrollview_path);
422  SVSync::StartProcess(prog, command.c_str());
423 
424  // Wait for server to show up.
425  // Note: There is no exception handling in case the server never turns up.
426 
427  Close();
428  stream_ = socket(addr_info->ai_family, addr_info->ai_socktype,
429  addr_info->ai_protocol);
430 
431  while (connect(stream_, addr_info->ai_addr,
432  addr_info->ai_addrlen) < 0) {
433  std::cout << "ScrollView: Waiting for server...\n";
434 #ifdef _WIN32
435  Sleep(1000);
436 #else
437  sleep(1);
438 #endif
439 
440  Close();
441  stream_ = socket(addr_info->ai_family, addr_info->ai_socktype,
442  addr_info->ai_protocol);
443  }
444  }
445  FreeAddrInfo(addr_info);
446 }
447 
449  delete[] msg_buffer_in_;
450 }
451 
452 #endif // GRAPHICS_DISABLED
static void StartProcess(const char *executable, const char *args)
Starts a new process.
Definition: svutil.cpp:120
char * Receive()
Definition: svutil.cpp:228
char * strtok_r(char *s1, const char *s2, char **lasts)
Definition: strtok_r.cpp:38
void Unlock()
Unlocks on a mutex.
Definition: svutil.cpp:78
SVMutex()
Sets up a new mutex.
Definition: svutil.cpp:62
static void ExitThread()
Signals a thread to exit.
Definition: svutil.cpp:111
static void StartThread(void *(*func)(void *), void *arg)
Create new thread.
Definition: svutil.cpp:87
#define FALSE
Definition: capi.h:46
const int kMaxMsgSize
Definition: svutil.cpp:108
void Flush()
Flush the buffer.
Definition: svutil.cpp:217
SVNetwork(const char *hostname, int port)
Set up a connection to hostname on port.
Definition: svutil.cpp:389
void Wait()
Wait on a semaphore.
Definition: svutil.cpp:199
void Send(const char *msg)
Put a message in the messagebuffer to the server and try to send it.
Definition: svutil.cpp:210
SVSemaphore()
Sets up a semaphore.
Definition: svutil.cpp:173
void Lock()
Locks on a mutex.
Definition: svutil.cpp:70
void Close()
Close the connection to the server.
Definition: svutil.cpp:276
void Signal()
Signal a semaphore.
Definition: svutil.cpp:189
~SVNetwork()
Destructor.
Definition: svutil.cpp:448