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.
15 #include "support/debug.h"
16 #include "support/FileName.h"
17 #include "support/unicode.h"
18 #include "support/lstrings.h"
20 #include <boost/filesystem/operations.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>
59 using ::boost::scoped_ptr;
60 namespace fs = ::boost::filesystem;
64 using support::FileName;
65 using support::prefixIs;
69 string itoa(unsigned int i)
72 sprintf(buf, "%d", i);
77 /// Returns the absolute pathnames of all lyx local sockets in
78 /// file system encoding.
79 /// Parts stolen from lyx::support::DirList().
80 vector<fs::path> lyxSockets(string const & dir, string const & pid)
82 vector<fs::path> dirlist;
84 fs::path dirpath(dir);
86 if (!fs::exists(dirpath) || !fs::is_directory(dirpath)) {
87 lyxerr << dir << " does not exist or is not a directory."
92 fs::directory_iterator beg((fs::path(dir)));
93 fs::directory_iterator end;
95 for (; beg != end; ++beg) {
96 if (prefixIs(beg->leaf(), "lyx_tmpdir" + pid)) {
97 fs::path lyxsocket = beg->path() / "lyxsocket";
98 if (fs::exists(lyxsocket)) {
99 dirlist.push_back(lyxsocket);
108 namespace socktools {
111 /// Connect to the socket \p name.
112 int connect(FileName const & name)
114 int fd; // File descriptor for the socket
115 sockaddr_un addr; // Structure that hold the socket address
117 string const encoded = name.toFilesystemEncoding();
118 // char sun_path[108]
119 string::size_type len = encoded.size();
121 cerr << "lyxclient: Socket address '" << name
122 << "' too long." << endl;
125 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
126 addr.sun_family = AF_UNIX;
127 encoded.copy(addr.sun_path, 107);
128 addr.sun_path[len] = '\0';
130 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
131 cerr << "lyxclient: Could not create socket descriptor: "
132 << strerror(errno) << endl;
136 reinterpret_cast<struct sockaddr *>(&addr),
137 sizeof(addr)) == -1) {
138 cerr << "lyxclient: Could not connect to socket " << name.absFilename()
139 << ": " << strerror(errno) << endl;
143 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
144 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
145 << strerror(errno) << endl;
153 } // namespace socktools
154 } // namespace support
158 /////////////////////////////////////////////////////////////////////
162 /////////////////////////////////////////////////////////////////////
184 void IOWatch::clear()
190 void IOWatch::addfd(int fd)
196 bool IOWatch::wait(double timeout)
199 to.tv_sec = static_cast<long int>(timeout);
200 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
202 return select(FD_SETSIZE, &act,
203 (fd_set *)0, (fd_set *)0, &to);
210 return select(FD_SETSIZE, &act,
211 (fd_set *)0, (fd_set *)0, (timeval *)0);
215 bool IOWatch::isset(int fd)
217 return FD_ISSET(fd, &act);
222 /////////////////////////////////////////////////////////////////////
226 /////////////////////////////////////////////////////////////////////
228 // Modified LyXDataSocket class for use with the client
229 class LyXDataSocket {
231 LyXDataSocket(FileName 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(FileName 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);
337 /////////////////////////////////////////////////////////////////////
341 /////////////////////////////////////////////////////////////////////
343 class CmdLineParser {
345 typedef int (*optfunc)(vector<docstring> const & args);
346 std::map<string, optfunc> helper;
347 std::map<string, bool> isset;
348 bool parse(int, char * []);
349 vector<char *> nonopt;
353 bool CmdLineParser::parse(int argc, char * argv[])
357 vector<docstring> args;
358 if (helper[argv[opt]]) {
359 isset[argv[opt]] = true;
361 while ((arg < argc) && (!helper[argv[arg]])) {
362 args.push_back(from_local8bit(argv[arg]));
365 int taken = helper[argv[opt]](args);
370 if (argv[opt][0] == '-') {
371 if ((argv[opt][1] == '-')
372 && (argv[opt][2]== '\0')) {
375 nonopt.push_back(argv[opt]);
380 cerr << "lyxclient: unknown option "
381 << argv[opt] << endl;
385 nonopt.push_back(argv[opt]);
391 // ~Class CmdLineParser -------------------------------------------------------
400 "Usage: lyxclient [options]\n"
402 " -a address set address of the lyx socket\n"
403 " -t directory set system temporary directory\n"
404 " -p pid select a running lyx by pidi\n"
405 " -c command send a single command and quit\n"
406 " -g file row send a command to go to file and row\n"
407 " -n name set client name\n"
408 " -h name display this help end exit\n"
409 "If -a is not used, lyxclient will use the arguments of -t and -p to look for\n"
410 "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set,\n"
411 "lyxclient will connect only to a lyx with the specified pid. Options -c and -g\n"
412 "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient\n"
413 "will read commands from standard input and disconnect when command read is BYE:"
418 int h(vector<docstring> const &)
425 docstring clientName =
426 from_ascii(support::itoa(::getppid()) + ">" + support::itoa(::getpid()));
428 int n(vector<docstring> const & arg)
430 if (arg.size() < 1) {
431 cerr << "lyxclient: The option -n requires 1 argument."
440 docstring singleCommand;
443 int c(vector<docstring> const & arg)
445 if (arg.size() < 1) {
446 cerr << "lyxclient: The option -c requires 1 argument."
450 singleCommand = arg[0];
455 int g(vector<docstring> const & arg)
457 if (arg.size() < 2) {
458 cerr << "lyxclient: The option -g requires 2 arguments."
462 singleCommand = "LYXCMD:server-goto-file-row "
469 // empty if LYXSOCKET is not set in the environment
470 docstring serverAddress;
473 int a(vector<docstring> const & arg)
475 if (arg.size() < 1) {
476 cerr << "lyxclient: The option -a requires 1 argument."
480 // -a supercedes LYXSOCKET environment variable
481 serverAddress = arg[0];
486 docstring mainTmp(from_ascii("/tmp"));
489 int t(vector<docstring> const & arg)
491 if (arg.size() < 1) {
492 cerr << "lyxclient: The option -t requires 1 argument."
501 string serverPid; // Init to empty string
504 int p(vector<docstring> const & arg)
506 if (arg.size() < 1) {
507 cerr << "lyxclient: The option -p requires 1 argument."
511 serverPid = to_ascii(arg[0]);
516 } // namespace cmdline
520 int main(int argc, char * argv[])
523 lyxerr.setStream(cerr);
525 char const * const lyxsocket = getenv("LYXSOCKET");
527 cmdline::serverAddress = from_local8bit(lyxsocket);
530 args.helper["-h"] = cmdline::h;
531 args.helper["-c"] = cmdline::c;
532 args.helper["-g"] = cmdline::g;
533 args.helper["-n"] = cmdline::n;
534 args.helper["-a"] = cmdline::a;
535 args.helper["-t"] = cmdline::t;
536 args.helper["-p"] = cmdline::p;
538 // Command line failure conditions:
539 if ((!args.parse(argc, argv))
540 || (args.isset["-c"] && args.isset["-g"])
541 || (args.isset["-a"] && args.isset["-p"])) {
546 scoped_ptr<LyXDataSocket> server;
548 if (!cmdline::serverAddress.empty()) {
549 server.reset(new LyXDataSocket(FileName(to_utf8(cmdline::serverAddress))));
550 if (!server->connected()) {
551 cerr << "lyxclient: " << "Could not connect to "
552 << to_utf8(cmdline::serverAddress) << endl;
556 // We have to look for an address.
557 // serverPid can be empty.
558 vector<fs::path> addrs = support::lyxSockets(to_filesystem8bit(cmdline::mainTmp), cmdline::serverPid);
559 vector<fs::path>::const_iterator addr = addrs.begin();
560 vector<fs::path>::const_iterator end = addrs.end();
561 for (; addr != end; ++addr) {
562 // Caution: addr->string() is in filesystem encoding
563 server.reset(new LyXDataSocket(FileName(to_utf8(from_filesystem8bit(addr->string())))));
564 if (server->connected())
566 lyxerr << "lyxclient: " << "Could not connect to "
567 << addr->string() << endl;
570 lyxerr << "lyxclient: No suitable server found."
574 cerr << "lyxclient: " << "Connected to " << addr->string() << endl;
577 int const serverfd = server->fd();
580 iowatch.addfd(serverfd);
582 // Used to read from server
586 server->writeln("HELLO:" + to_utf8(cmdline::clientName));
587 // wait at most 2 seconds until server responds
589 if (iowatch.isset(serverfd) && server->readln(answer)) {
590 if (prefixIs(answer, "BYE:")) {
591 cerr << "lyxclient: Server disconnected." << endl;
592 cout << answer << endl;
596 cerr << "lyxclient: No answer from server." << endl;
600 if (args.isset["-g"] || args.isset["-c"]) {
601 server->writeln(to_utf8(cmdline::singleCommand));
603 if (iowatch.isset(serverfd) && server->readln(answer)) {
605 if (prefixIs(answer, "ERROR:"))
609 cerr << "lyxclient: No answer from server." << endl;
614 // Take commands from stdin
615 iowatch.addfd(0); // stdin
616 bool saidbye = false;
617 while ((!saidbye) && server->connected()) {
619 if (iowatch.isset(0)) {
622 if (command == "BYE:") {
623 server->writeln("BYE:");
626 server->writeln("LYXCMD:" + command);
629 if (iowatch.isset(serverfd)) {
630 while(server->readln(answer))
631 cout << answer << endl;
641 void assertion_failed(char const* a, char const* b, char const* c, long d)
643 lyx::lyxerr << "Assertion failed: " << a << ' ' << b << ' ' << c << ' '