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 #include <sys/types.h>
27 #include <sys/select.h>
29 // socket(), connect()
30 #include <sys/socket.h>
42 using lyx::support::prefixIs;
44 using boost::scoped_ptr;
45 namespace fs = boost::filesystem;
57 string itoa(unsigned int i)
59 return boost::lexical_cast<string>(i);
63 // Parts stolen from lyx::support::DirList()
64 // Returns the absolute pathnames of all lyx local sockets
65 vector<fs::path> lyxSockets(string const & dir, string const & pid)
67 vector<fs::path> dirlist;
69 fs::path dirpath(dir);
71 if (!fs::exists(dirpath) || !fs::is_directory(dirpath)) {
72 lyxerr << dir << " does not exist or is not a directory."
77 fs::directory_iterator beg((fs::path(dir)));
78 fs::directory_iterator end;
80 for (; beg != end; ++beg) {
81 if (prefixIs(beg->leaf(), "lyx_tmpdir" + pid)) {
82 fs::path lyxsocket = *beg / "lyxsocket";
83 if (fs::exists(lyxsocket)) {
84 dirlist.push_back(lyxsocket);
96 int connect(string const & name)
98 int fd; // File descriptor for the socket
99 sockaddr_un addr; // Structure that hold the socket address
101 // char sun_path[108]
102 string::size_type len = name.size();
104 cerr << "lyxclient: Socket address '" << name
105 << "' too long." << endl;
108 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
109 addr.sun_family = AF_UNIX;
110 name.copy(addr.sun_path, 107);
111 addr.sun_path[len] = '\0';
113 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
114 cerr << "lyxclient: Could not create socket descriptor: "
115 << strerror(errno) << endl;
118 if (::connect(fd, (struct sockaddr *)&addr, SUN_LEN(&addr)) == -1) {
119 cerr << "lyxclient: Could not connect to socket " << name
120 << ": " << strerror(errno) << endl;
124 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
125 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
126 << strerror(errno) << endl;
134 } // namespace socktools
135 } // namespace support
139 // Class IOWatch ------------------------------------------------------------
160 void IOWatch::clear()
166 void IOWatch::addfd(int fd)
172 bool IOWatch::wait(double timeout)
175 to.tv_sec = static_cast<long int>(timeout);
176 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
178 return select(FD_SETSIZE, &act,
179 (fd_set *)0, (fd_set *)0, &to);
186 return select(FD_SETSIZE, &act,
187 (fd_set *)0, (fd_set *)0, (timeval *)0);
191 bool IOWatch::isset(int fd) {
192 return FD_ISSET(fd, &act);
194 // ~Class IOWatch ------------------------------------------------------------
197 // Class LyXDataSocket -------------------------------------------------------
198 // Modified LyXDataSocket class for use with the client
199 class LyXDataSocket {
201 LyXDataSocket(string const &);
203 // File descriptor of the connection
206 bool connected() const;
207 // Line buffered input from the socket
208 bool readln(string &);
209 // Write the string + '\n' to the socket
210 void writeln(string const &);
212 // File descriptor for the data socket
214 // True if the connection is up
216 // buffer for input data
221 LyXDataSocket::LyXDataSocket(string const & address)
223 if ((fd_ = support::socktools::connect(address)) == -1) {
231 LyXDataSocket::~LyXDataSocket()
237 int LyXDataSocket::fd() const
243 bool LyXDataSocket::connected() const
249 // Returns true if there was a complete line to input
250 // A line is of the form <key>:<value>
251 // A line not of this form will not be passed
252 // The line read is splitted and stored in 'key' and 'value'
253 bool LyXDataSocket::readln(string & line)
255 int const charbuf_size = 100;
256 char charbuf[charbuf_size]; // buffer for the ::read() system call
258 string::size_type pos;
260 // read and store characters in buffer
261 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
262 charbuf[count] = '\0'; // turn it into a c string
266 // Error conditions. The buffer must still be
267 // processed for lines read
268 if (count == 0) { // EOF -- connection closed
270 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
271 cerr << "lyxclient: IO error." << endl;
275 // Cut a line from buffer
276 if ((pos = buffer.find('\n')) == string::npos)
277 return false; // No complete line stored
278 line = buffer.substr(0, pos);
279 buffer = buffer.substr(pos + 1);
284 // Write a line of the form <key>:<value> to the socket
285 void LyXDataSocket::writeln(string const & line)
287 string linen(line + '\n');
288 int size = linen.size();
289 int written = ::write(fd_, linen.c_str(), size);
290 if (written < size) { // Allways mean end of connection.
291 if ((written == -1) && (errno == EPIPE)) {
292 // The program will also receive a SIGPIPE
293 // that must be catched
294 cerr << "lyxclient: connection closed while writing."
297 // Anything else, including errno == EAGAIN, must be
298 // considered IO error. EAGAIN should never happen
299 // when line is small
300 cerr << "lyxclient: IO error: " << strerror(errno);
305 // ~Class LyXDataSocket -------------------------------------------------------
308 // Class CmdLineParser -------------------------------------------------------
309 class CmdLineParser {
311 typedef int (*optfunc)(vector<char *> const & args);
312 std::map<string, optfunc> helper;
313 std::map<string, bool> isset;
314 bool parse(int, char * []);
315 vector<char *> nonopt;
319 bool CmdLineParser::parse(int argc, char * argv[])
324 if (helper[argv[opt]]) {
325 isset[argv[opt]] = true;
327 while ((arg < argc) && (!helper[argv[arg]])) {
328 args.push_back(argv[arg]);
331 int taken = helper[argv[opt]](args);
336 if (argv[opt][0] == '-') {
337 if ((argv[opt][1] == '-')
338 && (argv[opt][2]== '\0')) {
341 nonopt.push_back(argv[opt]);
346 cerr << "lyxclient: unknown option "
347 << argv[opt] << endl;
351 nonopt.push_back(argv[opt]);
357 // ~Class CmdLineParser -------------------------------------------------------
365 cerr << "Usage: lyxclient [options]" << endl
366 << "Options are:" << endl
367 << " -a address set address of the lyx socket" << endl
368 << " -t directory set system temporary directory" << endl
369 << " -p pid select a running lyx by pid" << endl
370 << " -c command send a single command and quit" << endl
371 << " -g file row send a command to go to file and row" << endl
372 << " -n name set client name" << endl
373 << " -h name display this help end exit" << endl
374 << "If -a is not used, lyxclient will use the arguments of -t and -p to look for" << endl
375 << "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set," << endl
376 << "lyxclient will connect only to a lyx with the specified pid. Options -c and -g" << endl
377 << "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient" << endl
378 << "will read commands from standard input and disconnect when command read is BYE:"
383 int h(vector<char *> const &)
390 string clientName(support::itoa(::getppid()) + ">" + support::itoa(::getpid()));
392 int n(vector<char *> const & arg)
394 if (arg.size() < 1) {
395 cerr << "lyxclient: The option -n requires 1 argument."
404 string singleCommand;
407 int c(vector<char *> const & arg)
409 if (arg.size() < 1) {
410 cerr << "lyxclient: The option -c requires 1 argument."
414 singleCommand = arg[0];
419 int g(vector<char *> const & arg)
421 if (arg.size() < 2) {
422 cerr << "lyxclient: The option -g requires 2 arguments."
426 singleCommand = "LYXCMD:server-goto-file-row "
427 + string(arg[0]) + ' '
433 // 0 if LYXSOCKET is not set in the environment
434 char * serverAddress = getenv("LYXSOCKET");
437 int a(vector<char *> const & arg)
439 if (arg.size() < 1) {
440 cerr << "lyxclient: The option -a requires 1 argument."
444 // -a supercedes LYXSOCKET environment variable
445 serverAddress = arg[0];
450 string mainTmp("/tmp");
453 int t(vector<char *> const & arg)
455 if (arg.size() < 1) {
456 cerr << "lyxclient: The option -t requires 1 argument."
465 string serverPid; // Init to empty string
468 int p(vector<char *> const & arg)
470 if (arg.size() < 1) {
471 cerr << "lyxclient: The option -p requires 1 argument."
480 } // namespace cmdline
486 int main(int argc, char * argv[])
488 lyxerr.rdbuf(cerr.rdbuf());
491 args.helper["-h"] = cmdline::h;
492 args.helper["-c"] = cmdline::c;
493 args.helper["-g"] = cmdline::g;
494 args.helper["-n"] = cmdline::n;
495 args.helper["-a"] = cmdline::a;
496 args.helper["-t"] = cmdline::t;
497 args.helper["-p"] = cmdline::p;
499 // Command line failure conditions:
500 if ((!args.parse(argc, argv))
501 || (args.isset["-c"] && args.isset["-g"])
502 || (args.isset["-a"] && args.isset["-p"])) {
507 scoped_ptr<LyXDataSocket> server;
509 if (cmdline::serverAddress) {
510 server.reset(new LyXDataSocket(cmdline::serverAddress));
511 if (!server->connected()) {
512 cerr << "lyxclient: " << "Could not connect to "
513 << cmdline::serverAddress << endl;
517 // We have to look for an address.
518 // serverPid can be empty.
519 vector<fs::path> addrs = support::lyxSockets(cmdline::mainTmp, cmdline::serverPid);
520 vector<fs::path>::const_iterator addr = addrs.begin();
521 vector<fs::path>::const_iterator end = addrs.end();
522 for (; addr != end; ++addr) {
523 server.reset(new LyXDataSocket(addr->string()));
524 if (server->connected())
526 lyxerr << "lyxclient: " << "Could not connect to "
527 << addr->string() << endl;
530 lyxerr << "lyxclient: No suitable server found."
534 cerr << "lyxclient: " << "Connected to " << addr->string() << endl;
537 int const serverfd = server->fd();
540 iowatch.addfd(serverfd);
542 // Used to read from server
546 server->writeln("HELLO:" + cmdline::clientName);
547 // wait at most 2 seconds until server responds
549 if (iowatch.isset(serverfd) && server->readln(answer)) {
550 if (prefixIs(answer, "BYE:")) {
551 cerr << "lyxclient: Server disconnected." << endl;
552 cout << answer << endl;
556 cerr << "lyxclient: No answer from server." << endl;
560 if (args.isset["-g"] || args.isset["-c"]) {
561 server->writeln(cmdline::singleCommand);
563 if (iowatch.isset(serverfd) && server->readln(answer)) {
565 if (prefixIs(answer, "ERROR:"))
569 cerr << "lyxclient: No answer from server." << endl;
574 // Take commands from stdin
575 iowatch.addfd(0); // stdin
576 bool saidbye = false;
577 while ((!saidbye) && server->connected()) {
579 if (iowatch.isset(0)) {
582 if (command == "BYE:") {
583 server->writeln("BYE:");
586 server->writeln("LYXCMD:" + command);
589 if (iowatch.isset(serverfd)) {
590 while(server->readln(answer))
591 cout << answer << endl;