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>
29 #include <sys/select.h>
31 // socket(), connect()
32 #include <sys/socket.h>
45 using lyx::support::prefixIs;
47 using boost::scoped_ptr;
48 namespace fs = boost::filesystem;
60 string itoa(unsigned int i)
62 return boost::lexical_cast<string>(i);
66 // Parts stolen from lyx::support::DirList()
67 // Returns the absolute pathnames of all lyx local sockets
68 vector<fs::path> lyxSockets(string const & dir, string const & pid)
70 vector<fs::path> dirlist;
72 fs::path dirpath(dir);
74 if (!fs::exists(dirpath) || !fs::is_directory(dirpath)) {
75 lyxerr << dir << " does not exist or is not a directory."
80 fs::directory_iterator beg((fs::path(dir)));
81 fs::directory_iterator end;
83 for (; beg != end; ++beg) {
84 if (prefixIs(beg->leaf(), "lyx_tmpdir" + pid)) {
85 fs::path lyxsocket = *beg / "lyxsocket";
86 if (fs::exists(lyxsocket)) {
87 dirlist.push_back(lyxsocket);
99 int connect(string const & name)
101 int fd; // File descriptor for the socket
102 sockaddr_un addr; // Structure that hold the socket address
104 // char sun_path[108]
105 string::size_type len = name.size();
107 cerr << "lyxclient: Socket address '" << name
108 << "' too long." << endl;
111 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
112 addr.sun_family = AF_UNIX;
113 name.copy(addr.sun_path, 107);
114 addr.sun_path[len] = '\0';
116 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
117 cerr << "lyxclient: Could not create socket descriptor: "
118 << strerror(errno) << endl;
122 reinterpret_cast<struct sockaddr *>(&addr),
123 sizeof(addr)) == -1) {
124 cerr << "lyxclient: Could not connect to socket " << name
125 << ": " << strerror(errno) << endl;
129 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
130 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
131 << strerror(errno) << endl;
139 } // namespace socktools
140 } // namespace support
144 // Class IOWatch ------------------------------------------------------------
165 void IOWatch::clear()
171 void IOWatch::addfd(int fd)
177 bool IOWatch::wait(double timeout)
180 to.tv_sec = static_cast<long int>(timeout);
181 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
183 return select(FD_SETSIZE, &act,
184 (fd_set *)0, (fd_set *)0, &to);
191 return select(FD_SETSIZE, &act,
192 (fd_set *)0, (fd_set *)0, (timeval *)0);
196 bool IOWatch::isset(int fd) {
197 return FD_ISSET(fd, &act);
199 // ~Class IOWatch ------------------------------------------------------------
202 // Class LyXDataSocket -------------------------------------------------------
203 // Modified LyXDataSocket class for use with the client
204 class LyXDataSocket {
206 LyXDataSocket(string const &);
208 // File descriptor of the connection
211 bool connected() const;
212 // Line buffered input from the socket
213 bool readln(string &);
214 // Write the string + '\n' to the socket
215 void writeln(string const &);
217 // File descriptor for the data socket
219 // True if the connection is up
221 // buffer for input data
226 LyXDataSocket::LyXDataSocket(string const & address)
228 if ((fd_ = support::socktools::connect(address)) == -1) {
236 LyXDataSocket::~LyXDataSocket()
242 int LyXDataSocket::fd() const
248 bool LyXDataSocket::connected() const
254 // Returns true if there was a complete line to input
255 // A line is of the form <key>:<value>
256 // A line not of this form will not be passed
257 // The line read is splitted and stored in 'key' and 'value'
258 bool LyXDataSocket::readln(string & line)
260 int const charbuf_size = 100;
261 char charbuf[charbuf_size]; // buffer for the ::read() system call
263 string::size_type pos;
265 // read and store characters in buffer
266 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
267 charbuf[count] = '\0'; // turn it into a c string
271 // Error conditions. The buffer must still be
272 // processed for lines read
273 if (count == 0) { // EOF -- connection closed
275 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
276 cerr << "lyxclient: IO error." << endl;
280 // Cut a line from buffer
281 if ((pos = buffer.find('\n')) == string::npos)
282 return false; // No complete line stored
283 line = buffer.substr(0, pos);
284 buffer = buffer.substr(pos + 1);
289 // Write a line of the form <key>:<value> to the socket
290 void LyXDataSocket::writeln(string const & line)
292 string linen(line + '\n');
293 int size = linen.size();
294 int written = ::write(fd_, linen.c_str(), size);
295 if (written < size) { // Allways mean end of connection.
296 if ((written == -1) && (errno == EPIPE)) {
297 // The program will also receive a SIGPIPE
298 // that must be catched
299 cerr << "lyxclient: connection closed while writing."
302 // Anything else, including errno == EAGAIN, must be
303 // considered IO error. EAGAIN should never happen
304 // when line is small
305 cerr << "lyxclient: IO error: " << strerror(errno);
310 // ~Class LyXDataSocket -------------------------------------------------------
313 // Class CmdLineParser -------------------------------------------------------
314 class CmdLineParser {
316 typedef int (*optfunc)(vector<char *> const & args);
317 std::map<string, optfunc> helper;
318 std::map<string, bool> isset;
319 bool parse(int, char * []);
320 vector<char *> nonopt;
324 bool CmdLineParser::parse(int argc, char * argv[])
329 if (helper[argv[opt]]) {
330 isset[argv[opt]] = true;
332 while ((arg < argc) && (!helper[argv[arg]])) {
333 args.push_back(argv[arg]);
336 int taken = helper[argv[opt]](args);
341 if (argv[opt][0] == '-') {
342 if ((argv[opt][1] == '-')
343 && (argv[opt][2]== '\0')) {
346 nonopt.push_back(argv[opt]);
351 cerr << "lyxclient: unknown option "
352 << argv[opt] << endl;
356 nonopt.push_back(argv[opt]);
362 // ~Class CmdLineParser -------------------------------------------------------
370 cerr << "Usage: lyxclient [options]" << endl
371 << "Options are:" << endl
372 << " -a address set address of the lyx socket" << endl
373 << " -t directory set system temporary directory" << endl
374 << " -p pid select a running lyx by pid" << endl
375 << " -c command send a single command and quit" << endl
376 << " -g file row send a command to go to file and row" << endl
377 << " -n name set client name" << endl
378 << " -h name display this help end exit" << endl
379 << "If -a is not used, lyxclient will use the arguments of -t and -p to look for" << endl
380 << "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set," << endl
381 << "lyxclient will connect only to a lyx with the specified pid. Options -c and -g" << endl
382 << "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient" << endl
383 << "will read commands from standard input and disconnect when command read is BYE:"
388 int h(vector<char *> const &)
395 string clientName(support::itoa(::getppid()) + ">" + support::itoa(::getpid()));
397 int n(vector<char *> const & arg)
399 if (arg.size() < 1) {
400 cerr << "lyxclient: The option -n requires 1 argument."
409 string singleCommand;
412 int c(vector<char *> const & arg)
414 if (arg.size() < 1) {
415 cerr << "lyxclient: The option -c requires 1 argument."
419 singleCommand = arg[0];
424 int g(vector<char *> const & arg)
426 if (arg.size() < 2) {
427 cerr << "lyxclient: The option -g requires 2 arguments."
431 singleCommand = "LYXCMD:server-goto-file-row "
432 + string(arg[0]) + ' '
438 // 0 if LYXSOCKET is not set in the environment
439 char * serverAddress = getenv("LYXSOCKET");
442 int a(vector<char *> const & arg)
444 if (arg.size() < 1) {
445 cerr << "lyxclient: The option -a requires 1 argument."
449 // -a supercedes LYXSOCKET environment variable
450 serverAddress = arg[0];
455 string mainTmp("/tmp");
458 int t(vector<char *> const & arg)
460 if (arg.size() < 1) {
461 cerr << "lyxclient: The option -t requires 1 argument."
470 string serverPid; // Init to empty string
473 int p(vector<char *> const & arg)
475 if (arg.size() < 1) {
476 cerr << "lyxclient: The option -p requires 1 argument."
485 } // namespace cmdline
491 int main(int argc, char * argv[])
493 lyxerr.rdbuf(cerr.rdbuf());
496 args.helper["-h"] = cmdline::h;
497 args.helper["-c"] = cmdline::c;
498 args.helper["-g"] = cmdline::g;
499 args.helper["-n"] = cmdline::n;
500 args.helper["-a"] = cmdline::a;
501 args.helper["-t"] = cmdline::t;
502 args.helper["-p"] = cmdline::p;
504 // Command line failure conditions:
505 if ((!args.parse(argc, argv))
506 || (args.isset["-c"] && args.isset["-g"])
507 || (args.isset["-a"] && args.isset["-p"])) {
512 scoped_ptr<LyXDataSocket> server;
514 if (cmdline::serverAddress) {
515 server.reset(new LyXDataSocket(cmdline::serverAddress));
516 if (!server->connected()) {
517 cerr << "lyxclient: " << "Could not connect to "
518 << cmdline::serverAddress << endl;
522 // We have to look for an address.
523 // serverPid can be empty.
524 vector<fs::path> addrs = support::lyxSockets(cmdline::mainTmp, cmdline::serverPid);
525 vector<fs::path>::const_iterator addr = addrs.begin();
526 vector<fs::path>::const_iterator end = addrs.end();
527 for (; addr != end; ++addr) {
528 server.reset(new LyXDataSocket(addr->string()));
529 if (server->connected())
531 lyxerr << "lyxclient: " << "Could not connect to "
532 << addr->string() << endl;
535 lyxerr << "lyxclient: No suitable server found."
539 cerr << "lyxclient: " << "Connected to " << addr->string() << endl;
542 int const serverfd = server->fd();
545 iowatch.addfd(serverfd);
547 // Used to read from server
551 server->writeln("HELLO:" + cmdline::clientName);
552 // wait at most 2 seconds until server responds
554 if (iowatch.isset(serverfd) && server->readln(answer)) {
555 if (prefixIs(answer, "BYE:")) {
556 cerr << "lyxclient: Server disconnected." << endl;
557 cout << answer << endl;
561 cerr << "lyxclient: No answer from server." << endl;
565 if (args.isset["-g"] || args.isset["-c"]) {
566 server->writeln(cmdline::singleCommand);
568 if (iowatch.isset(serverfd) && server->readln(answer)) {
570 if (prefixIs(answer, "ERROR:"))
574 cerr << "lyxclient: No answer from server." << endl;
579 // Take commands from stdin
580 iowatch.addfd(0); // stdin
581 bool saidbye = false;
582 while ((!saidbye) && server->connected()) {
584 if (iowatch.isset(0)) {
587 if (command == "BYE:") {
588 server->writeln("BYE:");
591 server->writeln("LYXCMD:" + command);
594 if (iowatch.isset(serverfd)) {
595 while(server->readln(answer))
596 cout << answer << endl;