3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author João Luis M. Assirati
7 * \author Lars Gullik Bjønnes
9 * Full author contact details are available in file CREDITS.
16 #include "support/unicode.h"
17 #include "support/lstrings.h"
19 #include <boost/filesystem/operations.hpp>
20 #include <boost/lexical_cast.hpp>
21 #include <boost/scoped_ptr.hpp>
23 // getpid(), getppid()
24 #ifdef HAVE_SYS_TYPES_H
25 # include <sys/types.h>
32 #ifdef HAVE_SYS_TIME_H
33 # include <sys/time.h>
37 #ifdef HAVE_SYS_SELECT_H
38 # include <sys/select.h>
41 // socket(), connect()
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
60 using lyx::support::prefixIs;
62 using boost::scoped_ptr;
63 namespace fs = boost::filesystem;
73 IconvProcessor & utf8ToUcs4()
75 static IconvProcessor iconv(ucs4_codeset, "UTF-8");
82 string itoa(unsigned int i)
84 return boost::lexical_cast<string>(i);
88 /// Returns the absolute pathnames of all lyx local sockets in
89 /// file system encoding.
90 /// Parts stolen from lyx::support::DirList().
91 vector<fs::path> lyxSockets(string const & dir, string const & pid)
93 vector<fs::path> dirlist;
95 fs::path dirpath(dir);
97 if (!fs::exists(dirpath) || !fs::is_directory(dirpath)) {
98 lyxerr << dir << " does not exist or is not a directory."
103 fs::directory_iterator beg((fs::path(dir)));
104 fs::directory_iterator end;
106 for (; beg != end; ++beg) {
107 if (prefixIs(beg->leaf(), "lyx_tmpdir" + pid)) {
108 fs::path lyxsocket = beg->path() / "lyxsocket";
109 if (fs::exists(lyxsocket)) {
110 dirlist.push_back(lyxsocket);
119 namespace socktools {
122 /// Connect to the socket \p name.
123 /// Caution: \p name is in filesystem encoding
124 int connect(string const & name)
126 int fd; // File descriptor for the socket
127 sockaddr_un addr; // Structure that hold the socket address
129 // char sun_path[108]
130 string::size_type len = name.size();
132 cerr << "lyxclient: Socket address '" << name
133 << "' too long." << endl;
136 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
137 addr.sun_family = AF_UNIX;
138 name.copy(addr.sun_path, 107);
139 addr.sun_path[len] = '\0';
141 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
142 cerr << "lyxclient: Could not create socket descriptor: "
143 << strerror(errno) << endl;
147 reinterpret_cast<struct sockaddr *>(&addr),
148 sizeof(addr)) == -1) {
149 cerr << "lyxclient: Could not connect to socket " << name
150 << ": " << strerror(errno) << endl;
154 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
155 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
156 << strerror(errno) << endl;
164 } // namespace socktools
165 } // namespace support
169 // Class IOWatch ------------------------------------------------------------
190 void IOWatch::clear()
196 void IOWatch::addfd(int fd)
202 bool IOWatch::wait(double timeout)
205 to.tv_sec = static_cast<long int>(timeout);
206 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
208 return select(FD_SETSIZE, &act,
209 (fd_set *)0, (fd_set *)0, &to);
216 return select(FD_SETSIZE, &act,
217 (fd_set *)0, (fd_set *)0, (timeval *)0);
221 bool IOWatch::isset(int fd) {
222 return FD_ISSET(fd, &act);
224 // ~Class IOWatch ------------------------------------------------------------
227 // Class LyXDataSocket -------------------------------------------------------
228 // Modified LyXDataSocket class for use with the client
229 class LyXDataSocket {
231 LyXDataSocket(string const &);
233 // File descriptor of the connection
236 bool connected() const;
237 // Line buffered input from the socket
238 bool readln(string &);
239 // Write the string + '\n' to the socket
240 void writeln(string const &);
242 // File descriptor for the data socket
244 // True if the connection is up
246 // buffer for input data
251 LyXDataSocket::LyXDataSocket(string const & address)
253 if ((fd_ = support::socktools::connect(address)) == -1) {
261 LyXDataSocket::~LyXDataSocket()
267 int LyXDataSocket::fd() const
273 bool LyXDataSocket::connected() const
279 // Returns true if there was a complete line to input
280 // A line is of the form <key>:<value>
281 // A line not of this form will not be passed
282 // The line read is splitted and stored in 'key' and 'value'
283 bool LyXDataSocket::readln(string & line)
285 int const charbuf_size = 100;
286 char charbuf[charbuf_size]; // buffer for the ::read() system call
288 string::size_type pos;
290 // read and store characters in buffer
291 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
292 charbuf[count] = '\0'; // turn it into a c string
296 // Error conditions. The buffer must still be
297 // processed for lines read
298 if (count == 0) { // EOF -- connection closed
300 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
301 cerr << "lyxclient: IO error." << endl;
305 // Cut a line from buffer
306 if ((pos = buffer.find('\n')) == string::npos)
307 return false; // No complete line stored
308 line = buffer.substr(0, pos);
309 buffer = buffer.substr(pos + 1);
314 // Write a line of the form <key>:<value> to the socket
315 void LyXDataSocket::writeln(string const & line)
317 string linen(line + '\n');
318 int size = linen.size();
319 int written = ::write(fd_, linen.c_str(), size);
320 if (written < size) { // Allways mean end of connection.
321 if ((written == -1) && (errno == EPIPE)) {
322 // The program will also receive a SIGPIPE
323 // that must be catched
324 cerr << "lyxclient: connection closed while writing."
327 // Anything else, including errno == EAGAIN, must be
328 // considered IO error. EAGAIN should never happen
329 // when line is small
330 cerr << "lyxclient: IO error: " << strerror(errno);
335 // ~Class LyXDataSocket -------------------------------------------------------
338 // Class CmdLineParser -------------------------------------------------------
339 class CmdLineParser {
341 typedef int (*optfunc)(vector<docstring> const & args);
342 std::map<string, optfunc> helper;
343 std::map<string, bool> isset;
344 bool parse(int, char * []);
345 vector<char *> nonopt;
349 bool CmdLineParser::parse(int argc, char * argv[])
353 vector<docstring> args;
354 if (helper[argv[opt]]) {
355 isset[argv[opt]] = true;
357 while ((arg < argc) && (!helper[argv[arg]])) {
358 args.push_back(from_local8bit(argv[arg]));
361 int taken = helper[argv[opt]](args);
366 if (argv[opt][0] == '-') {
367 if ((argv[opt][1] == '-')
368 && (argv[opt][2]== '\0')) {
371 nonopt.push_back(argv[opt]);
376 cerr << "lyxclient: unknown option "
377 << argv[opt] << endl;
381 nonopt.push_back(argv[opt]);
387 // ~Class CmdLineParser -------------------------------------------------------
395 cerr << "Usage: lyxclient [options]" << endl
396 << "Options are:" << endl
397 << " -a address set address of the lyx socket" << endl
398 << " -t directory set system temporary directory" << endl
399 << " -p pid select a running lyx by pid" << endl
400 << " -c command send a single command and quit" << endl
401 << " -g file row send a command to go to file and row" << endl
402 << " -n name set client name" << endl
403 << " -h name display this help end exit" << endl
404 << "If -a is not used, lyxclient will use the arguments of -t and -p to look for" << endl
405 << "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set," << endl
406 << "lyxclient will connect only to a lyx with the specified pid. Options -c and -g" << endl
407 << "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient" << endl
408 << "will read commands from standard input and disconnect when command read is BYE:"
413 int h(vector<docstring> const &)
420 docstring clientName(from_ascii(support::itoa(::getppid()) + ">" + support::itoa(::getpid())));
422 int n(vector<docstring> const & arg)
424 if (arg.size() < 1) {
425 cerr << "lyxclient: The option -n requires 1 argument."
434 docstring singleCommand;
437 int c(vector<docstring> const & arg)
439 if (arg.size() < 1) {
440 cerr << "lyxclient: The option -c requires 1 argument."
444 singleCommand = arg[0];
449 int g(vector<docstring> const & arg)
451 if (arg.size() < 2) {
452 cerr << "lyxclient: The option -g requires 2 arguments."
456 singleCommand = "LYXCMD:server-goto-file-row "
463 // empty if LYXSOCKET is not set in the environment
464 docstring serverAddress;
467 int a(vector<docstring> const & arg)
469 if (arg.size() < 1) {
470 cerr << "lyxclient: The option -a requires 1 argument."
474 // -a supercedes LYXSOCKET environment variable
475 serverAddress = arg[0];
480 docstring mainTmp(from_ascii("/tmp"));
483 int t(vector<docstring> const & arg)
485 if (arg.size() < 1) {
486 cerr << "lyxclient: The option -t requires 1 argument."
495 string serverPid; // Init to empty string
498 int p(vector<docstring> const & arg)
500 if (arg.size() < 1) {
501 cerr << "lyxclient: The option -p requires 1 argument."
505 serverPid = to_ascii(arg[0]);
510 } // namespace cmdline
515 int main(int argc, char * argv[])
518 lyxerr.rdbuf(cerr.rdbuf());
520 char const * const lyxsocket = getenv("LYXSOCKET");
522 cmdline::serverAddress = from_local8bit(lyxsocket);
525 args.helper["-h"] = cmdline::h;
526 args.helper["-c"] = cmdline::c;
527 args.helper["-g"] = cmdline::g;
528 args.helper["-n"] = cmdline::n;
529 args.helper["-a"] = cmdline::a;
530 args.helper["-t"] = cmdline::t;
531 args.helper["-p"] = cmdline::p;
533 // Command line failure conditions:
534 if ((!args.parse(argc, argv))
535 || (args.isset["-c"] && args.isset["-g"])
536 || (args.isset["-a"] && args.isset["-p"])) {
541 scoped_ptr<LyXDataSocket> server;
543 if (!cmdline::serverAddress.empty()) {
544 server.reset(new LyXDataSocket(to_utf8(cmdline::serverAddress)));
545 if (!server->connected()) {
546 cerr << "lyxclient: " << "Could not connect to "
547 << to_utf8(cmdline::serverAddress) << endl;
551 // We have to look for an address.
552 // serverPid can be empty.
553 vector<fs::path> addrs = support::lyxSockets(to_utf8(cmdline::mainTmp), cmdline::serverPid);
554 vector<fs::path>::const_iterator addr = addrs.begin();
555 vector<fs::path>::const_iterator end = addrs.end();
556 for (; addr != end; ++addr) {
557 // Caution: addr->string() is in filesystem encoding
558 server.reset(new LyXDataSocket(addr->string()));
559 if (server->connected())
561 lyxerr << "lyxclient: " << "Could not connect to "
562 << addr->string() << endl;
565 lyxerr << "lyxclient: No suitable server found."
569 cerr << "lyxclient: " << "Connected to " << addr->string() << endl;
572 int const serverfd = server->fd();
575 iowatch.addfd(serverfd);
577 // Used to read from server
581 server->writeln("HELLO:" + to_utf8(cmdline::clientName));
582 // wait at most 2 seconds until server responds
584 if (iowatch.isset(serverfd) && server->readln(answer)) {
585 if (prefixIs(answer, "BYE:")) {
586 cerr << "lyxclient: Server disconnected." << endl;
587 cout << answer << endl;
591 cerr << "lyxclient: No answer from server." << endl;
595 if (args.isset["-g"] || args.isset["-c"]) {
596 server->writeln(to_utf8(cmdline::singleCommand));
598 if (iowatch.isset(serverfd) && server->readln(answer)) {
600 if (prefixIs(answer, "ERROR:"))
604 cerr << "lyxclient: No answer from server." << endl;
609 // Take commands from stdin
610 iowatch.addfd(0); // stdin
611 bool saidbye = false;
612 while ((!saidbye) && server->connected()) {
614 if (iowatch.isset(0)) {
617 if (command == "BYE:") {
618 server->writeln("BYE:");
621 server->writeln("LYXCMD:" + command);
624 if (iowatch.isset(serverfd)) {
625 while(server->readln(answer))
626 cout << answer << endl;
636 void assertion_failed(char const* a, char const* b, char const* c, long d)
638 lyx::lyxerr << "Assertion failed: " << a << ' ' << b << ' ' << c << ' '