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/lstrings.h"
18 #include <boost/filesystem/operations.hpp>
19 #include <boost/lexical_cast.hpp>
20 #include <boost/scoped_ptr.hpp>
22 // getpid(), getppid()
23 #ifdef HAVE_SYS_TYPES_H
24 # include <sys/types.h>
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
36 #ifdef HAVE_SYS_SELECT_H
37 # include <sys/select.h>
40 // socket(), connect()
41 #ifdef HAVE_SYS_SOCKET_H
42 # include <sys/socket.h>
59 using lyx::support::prefixIs;
61 using boost::scoped_ptr;
62 namespace fs = boost::filesystem;
74 string itoa(unsigned int i)
76 return boost::lexical_cast<string>(i);
80 // Parts stolen from lyx::support::DirList()
81 // Returns the absolute pathnames of all lyx local sockets
82 vector<fs::path> lyxSockets(string const & dir, string const & pid)
84 vector<fs::path> dirlist;
86 fs::path dirpath(dir);
88 if (!fs::exists(dirpath) || !fs::is_directory(dirpath)) {
89 lyxerr << dir << " does not exist or is not a directory."
94 fs::directory_iterator beg((fs::path(dir)));
95 fs::directory_iterator end;
97 for (; beg != end; ++beg) {
98 if (prefixIs(beg->leaf(), "lyx_tmpdir" + pid)) {
99 fs::path lyxsocket = beg->path() / "lyxsocket";
100 if (fs::exists(lyxsocket)) {
101 dirlist.push_back(lyxsocket);
110 namespace socktools {
113 int connect(string const & name)
115 int fd; // File descriptor for the socket
116 sockaddr_un addr; // Structure that hold the socket address
118 // char sun_path[108]
119 string::size_type len = name.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 name.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
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 // Class IOWatch ------------------------------------------------------------
179 void IOWatch::clear()
185 void IOWatch::addfd(int fd)
191 bool IOWatch::wait(double timeout)
194 to.tv_sec = static_cast<long int>(timeout);
195 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
197 return select(FD_SETSIZE, &act,
198 (fd_set *)0, (fd_set *)0, &to);
205 return select(FD_SETSIZE, &act,
206 (fd_set *)0, (fd_set *)0, (timeval *)0);
210 bool IOWatch::isset(int fd) {
211 return FD_ISSET(fd, &act);
213 // ~Class IOWatch ------------------------------------------------------------
216 // Class LyXDataSocket -------------------------------------------------------
217 // Modified LyXDataSocket class for use with the client
218 class LyXDataSocket {
220 LyXDataSocket(string const &);
222 // File descriptor of the connection
225 bool connected() const;
226 // Line buffered input from the socket
227 bool readln(string &);
228 // Write the string + '\n' to the socket
229 void writeln(string const &);
231 // File descriptor for the data socket
233 // True if the connection is up
235 // buffer for input data
240 LyXDataSocket::LyXDataSocket(string const & address)
242 if ((fd_ = support::socktools::connect(address)) == -1) {
250 LyXDataSocket::~LyXDataSocket()
256 int LyXDataSocket::fd() const
262 bool LyXDataSocket::connected() const
268 // Returns true if there was a complete line to input
269 // A line is of the form <key>:<value>
270 // A line not of this form will not be passed
271 // The line read is splitted and stored in 'key' and 'value'
272 bool LyXDataSocket::readln(string & line)
274 int const charbuf_size = 100;
275 char charbuf[charbuf_size]; // buffer for the ::read() system call
277 string::size_type pos;
279 // read and store characters in buffer
280 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
281 charbuf[count] = '\0'; // turn it into a c string
285 // Error conditions. The buffer must still be
286 // processed for lines read
287 if (count == 0) { // EOF -- connection closed
289 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
290 cerr << "lyxclient: IO error." << endl;
294 // Cut a line from buffer
295 if ((pos = buffer.find('\n')) == string::npos)
296 return false; // No complete line stored
297 line = buffer.substr(0, pos);
298 buffer = buffer.substr(pos + 1);
303 // Write a line of the form <key>:<value> to the socket
304 void LyXDataSocket::writeln(string const & line)
306 string linen(line + '\n');
307 int size = linen.size();
308 int written = ::write(fd_, linen.c_str(), size);
309 if (written < size) { // Allways mean end of connection.
310 if ((written == -1) && (errno == EPIPE)) {
311 // The program will also receive a SIGPIPE
312 // that must be catched
313 cerr << "lyxclient: connection closed while writing."
316 // Anything else, including errno == EAGAIN, must be
317 // considered IO error. EAGAIN should never happen
318 // when line is small
319 cerr << "lyxclient: IO error: " << strerror(errno);
324 // ~Class LyXDataSocket -------------------------------------------------------
327 // Class CmdLineParser -------------------------------------------------------
328 class CmdLineParser {
330 typedef int (*optfunc)(vector<char *> const & args);
331 std::map<string, optfunc> helper;
332 std::map<string, bool> isset;
333 bool parse(int, char * []);
334 vector<char *> nonopt;
338 bool CmdLineParser::parse(int argc, char * argv[])
343 if (helper[argv[opt]]) {
344 isset[argv[opt]] = true;
346 while ((arg < argc) && (!helper[argv[arg]])) {
347 args.push_back(argv[arg]);
350 int taken = helper[argv[opt]](args);
355 if (argv[opt][0] == '-') {
356 if ((argv[opt][1] == '-')
357 && (argv[opt][2]== '\0')) {
360 nonopt.push_back(argv[opt]);
365 cerr << "lyxclient: unknown option "
366 << argv[opt] << endl;
370 nonopt.push_back(argv[opt]);
376 // ~Class CmdLineParser -------------------------------------------------------
384 cerr << "Usage: lyxclient [options]" << endl
385 << "Options are:" << endl
386 << " -a address set address of the lyx socket" << endl
387 << " -t directory set system temporary directory" << endl
388 << " -p pid select a running lyx by pid" << endl
389 << " -c command send a single command and quit" << endl
390 << " -g file row send a command to go to file and row" << endl
391 << " -n name set client name" << endl
392 << " -h name display this help end exit" << endl
393 << "If -a is not used, lyxclient will use the arguments of -t and -p to look for" << endl
394 << "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set," << endl
395 << "lyxclient will connect only to a lyx with the specified pid. Options -c and -g" << endl
396 << "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient" << endl
397 << "will read commands from standard input and disconnect when command read is BYE:"
402 int h(vector<char *> const &)
409 string clientName(support::itoa(::getppid()) + ">" + support::itoa(::getpid()));
411 int n(vector<char *> const & arg)
413 if (arg.size() < 1) {
414 cerr << "lyxclient: The option -n requires 1 argument."
423 string singleCommand;
426 int c(vector<char *> const & arg)
428 if (arg.size() < 1) {
429 cerr << "lyxclient: The option -c requires 1 argument."
433 singleCommand = arg[0];
438 int g(vector<char *> const & arg)
440 if (arg.size() < 2) {
441 cerr << "lyxclient: The option -g requires 2 arguments."
445 singleCommand = "LYXCMD:server-goto-file-row "
446 + string(arg[0]) + ' '
452 // 0 if LYXSOCKET is not set in the environment
453 char * serverAddress = getenv("LYXSOCKET");
456 int a(vector<char *> const & arg)
458 if (arg.size() < 1) {
459 cerr << "lyxclient: The option -a requires 1 argument."
463 // -a supercedes LYXSOCKET environment variable
464 serverAddress = arg[0];
469 string mainTmp("/tmp");
472 int t(vector<char *> const & arg)
474 if (arg.size() < 1) {
475 cerr << "lyxclient: The option -t requires 1 argument."
484 string serverPid; // Init to empty string
487 int p(vector<char *> const & arg)
489 if (arg.size() < 1) {
490 cerr << "lyxclient: The option -p requires 1 argument."
499 } // namespace cmdline
506 int main(int argc, char * argv[])
509 lyxerr.rdbuf(cerr.rdbuf());
512 args.helper["-h"] = cmdline::h;
513 args.helper["-c"] = cmdline::c;
514 args.helper["-g"] = cmdline::g;
515 args.helper["-n"] = cmdline::n;
516 args.helper["-a"] = cmdline::a;
517 args.helper["-t"] = cmdline::t;
518 args.helper["-p"] = cmdline::p;
520 // Command line failure conditions:
521 if ((!args.parse(argc, argv))
522 || (args.isset["-c"] && args.isset["-g"])
523 || (args.isset["-a"] && args.isset["-p"])) {
528 scoped_ptr<LyXDataSocket> server;
530 if (cmdline::serverAddress) {
531 server.reset(new LyXDataSocket(cmdline::serverAddress));
532 if (!server->connected()) {
533 cerr << "lyxclient: " << "Could not connect to "
534 << cmdline::serverAddress << endl;
538 // We have to look for an address.
539 // serverPid can be empty.
540 vector<fs::path> addrs = support::lyxSockets(cmdline::mainTmp, cmdline::serverPid);
541 vector<fs::path>::const_iterator addr = addrs.begin();
542 vector<fs::path>::const_iterator end = addrs.end();
543 for (; addr != end; ++addr) {
544 server.reset(new LyXDataSocket(addr->string()));
545 if (server->connected())
547 lyxerr << "lyxclient: " << "Could not connect to "
548 << addr->string() << endl;
551 lyxerr << "lyxclient: No suitable server found."
555 cerr << "lyxclient: " << "Connected to " << addr->string() << endl;
558 int const serverfd = server->fd();
561 iowatch.addfd(serverfd);
563 // Used to read from server
567 server->writeln("HELLO:" + cmdline::clientName);
568 // wait at most 2 seconds until server responds
570 if (iowatch.isset(serverfd) && server->readln(answer)) {
571 if (prefixIs(answer, "BYE:")) {
572 cerr << "lyxclient: Server disconnected." << endl;
573 cout << answer << endl;
577 cerr << "lyxclient: No answer from server." << endl;
581 if (args.isset["-g"] || args.isset["-c"]) {
582 server->writeln(cmdline::singleCommand);
584 if (iowatch.isset(serverfd) && server->readln(answer)) {
586 if (prefixIs(answer, "ERROR:"))
590 cerr << "lyxclient: No answer from server." << endl;
595 // Take commands from stdin
596 iowatch.addfd(0); // stdin
597 bool saidbye = false;
598 while ((!saidbye) && server->connected()) {
600 if (iowatch.isset(0)) {
603 if (command == "BYE:") {
604 server->writeln("BYE:");
607 server->writeln("LYXCMD:" + command);
610 if (iowatch.isset(serverfd)) {
611 while(server->readln(answer))
612 cout << answer << endl;
622 void assertion_failed(char const* a, char const* b, char const* c, long d)
624 lyx::lyxerr << "Assertion failed: " << a << ' ' << b << ' ' << c << ' '