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
8 * Full author contact details are available in file CREDITS.
17 // getpid(), getppid()
18 #include <sys/types.h>
22 #include <sys/select.h>
24 // opendir(), closedir(), readdir()
25 #include <sys/types.h>
31 // socket(), connect()
32 #include <sys/socket.h>
49 string itoa(unsigned int i)
55 while((0 < i) && (i <= 9)) {
56 str = static_cast<char>('0' + i % 10) + str;
64 bool prefixIs(string const & a, string const & pre)
66 char const * p_a = a.c_str();
67 char const * p_pre = pre.c_str();
68 while ((*p_a != '\0') && (*p_pre != '\0') && (*p_a == *p_pre)) {
72 if (*p_pre == '\0') return true;
77 // Parts stolen from lyx::support::DirList()
78 // Returns pathnames begining with dir and ending with
79 // pathname separator (/ in unix)
80 vector<string> lyxSockets(string const & dir, string const & pid)
82 vector<string> dirlist;
83 DIR * dirp = ::opendir(dir.c_str());
85 cerr << "lyxclient: Could not read dir " << dir
86 << ": " << strerror(errno);
91 while ((dire = ::readdir(dirp))) {
92 string const fil = dire->d_name;
93 if (prefixIs(fil, "lyx_tmpdir" + pid)) {
94 string lyxsocket = dir + '/' + fil + "/lyxsocket";
96 // not checking if it is a socket -- just if it exists
97 if (!::stat(lyxsocket.c_str(), &status)) {
98 dirlist.push_back(lyxsocket);
107 namespace socktools {
109 int connect(string const & name)
111 int fd; // File descriptor for the socket
112 sockaddr_un addr; // Structure that hold the socket address
114 // char sun_path[108]
115 string::size_type len = name.size();
117 cerr << "lyxclient: Socket address '" << name
118 << "' too long." << endl;
121 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
122 addr.sun_family = AF_UNIX;
123 name.copy(addr.sun_path, 107);
124 addr.sun_path[len] = '\0';
126 if((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
127 cerr << "lyxclient: Could not create socket: "
128 << strerror(errno) << endl;
131 if(::connect(fd, (struct sockaddr *)&addr, SUN_LEN(&addr)) == -1) {
132 cerr << "lyxclient: Could not connect to socket " << name
133 << ": " << strerror(errno) << endl;
137 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
138 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
139 << strerror(errno) << endl;
146 } // namespace socktools
147 } // namespace support
151 // Class IOWatch ------------------------------------------------------------
170 void IOWatch::clear() {
173 void IOWatch::addfd(int fd) {
176 bool IOWatch::wait(double timeout) {
178 to.tv_sec = static_cast<long int>(timeout);
179 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
181 return select(FD_SETSIZE, &act,
182 (fd_set *)0, (fd_set *)0, &to);
184 bool IOWatch::wait() {
186 return select(FD_SETSIZE, &act,
187 (fd_set *)0, (fd_set *)0, (timeval *)0);
189 bool IOWatch::isset(int fd) {
190 return FD_ISSET(fd, &act);
192 // ~Class IOWatch ------------------------------------------------------------
195 // Class LyXDataSocket -------------------------------------------------------
196 // Modified LyXDataSocket class for use with the client
200 LyXDataSocket(string const &);
202 // File descriptor of the connection
205 bool connected() const;
206 // Line buffered input from the socket
207 bool readln(string &);
208 // Write the string + '\n' to the socket
209 void writeln(string const &);
212 // File descriptor for the data socket
214 // True if the connection is up
216 // buffer for input data
220 LyXDataSocket::LyXDataSocket(string const & address)
222 if ((fd_ = support::socktools::connect(address)) == -1) {
229 LyXDataSocket::~LyXDataSocket()
234 int LyXDataSocket::fd() const
239 bool LyXDataSocket::connected() const
244 // Returns true if there was a complete line to input
245 // A line is of the form <key>:<value>
246 // A line not of this form will not be passed
247 // The line read is splitted and stored in 'key' and 'value'
248 bool LyXDataSocket::readln(string & line)
250 int const charbuf_size = 100;
251 char charbuf[charbuf_size]; // buffer for the ::read() system call
253 string::size_type pos;
255 // read and store characters in buffer
256 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
257 charbuf[count] = '\0'; // turn it into a c string
261 // Error conditions. The buffer must still be
262 // processed for lines read
263 if (count == 0) { // EOF -- connection closed
265 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
266 cerr << "lyxclient: IO error." << endl;
270 // Cut a line from buffer
271 if ((pos = buffer.find('\n')) == string::npos)
272 return false; // No complete line stored
273 line = buffer.substr(0, pos);
274 buffer = buffer.substr(pos + 1);
278 // Write a line of the form <key>:<value> to the socket
279 void LyXDataSocket::writeln(string const & line)
281 string linen(line + '\n');
282 int size = linen.size();
283 int written = ::write(fd_, linen.c_str(), size);
284 if (written < size) { // Allways mean end of connection.
285 if ((written == -1) && (errno == EPIPE)) {
286 // The program will also receive a SIGPIPE
287 // that must be catched
288 cerr << "lyxclient: connection closed while writing."
291 // Anything else, including errno == EAGAIN, must be
292 // considered IO error. EAGAIN should never happen
293 // when line is small
294 cerr << "lyxclient: IO error: " << strerror(errno);
299 // ~Class LyXDataSocket -------------------------------------------------------
302 // Class CmdLineParser -------------------------------------------------------
306 typedef int (*optfunc)(vector<char *> const & args);
307 std::map<string, optfunc> helper;
308 std::map<string, bool> isset;
309 bool parse(int, char * []);
310 vector<char *> nonopt;
313 bool CmdLineParser::parse(int argc, char * argv[])
318 if(helper[argv[opt]]) {
319 isset[argv[opt]] = true;
321 while((arg < argc) && (!helper[argv[arg]])) {
322 args.push_back(argv[arg]);
325 int taken = helper[argv[opt]](args);
326 if(taken == -1) return false;
329 if(argv[opt][0] == '-') {
330 if((argv[opt][1] == '-')
331 && (argv[opt][2]== '\0')) {
334 nonopt.push_back(argv[opt]);
339 cerr << "lyxclient: unknown option "
340 << argv[opt] << endl;
344 nonopt.push_back(argv[opt]);
350 // ~Class CmdLineParser -------------------------------------------------------
358 cerr << "Usage: lyxclient [options]" << endl
359 << "Options are:" << endl
360 << " -a address set address of the lyx socket" << endl
361 << " -t directory set system temporary directory" << endl
362 << " -p pid select a running lyx by pid" << endl
363 << " -c command send a single command and quit" << endl
364 << " -g file row send a command to go to file and row" << endl
365 << " -n name set client name" << endl
366 << " -h name display this help end exit" << endl
367 << "If -a is not used, lyxclient will use the arguments of -t and -p to look for" << endl
368 << "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set," << endl
369 << "lyxclient will connect only to a lyx with the specified pid. Options -c and -g" << endl
370 << "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient" << endl
371 << "will read commands from standard input and disconnect when command read is BYE:"
375 int h(vector<char *> const & arg)
381 string clientName(support::itoa(::getppid()) + ">" + support::itoa(::getpid()));
382 int n(vector<char *> const & arg)
385 cerr << "lyxclient: The option -n requires 1 argument."
393 string singleCommand;
394 int c(vector<char *> const & arg)
397 cerr << "lyxclient: The option -c requires 1 argument."
401 singleCommand = arg[0];
405 int g(vector<char *> const & arg)
408 cerr << "lyxclient: The option -g requires 2 arguments."
412 singleCommand = "LYXCMD:server-goto-file-row "
413 + static_cast<string>(arg[0]) + ' '
414 + static_cast<string>(arg[1]);
418 char * serverAddress;
419 int a(vector<char *> const & arg)
422 cerr << "lyxclient: The option -a requires 1 argument."
426 serverAddress = arg[0];
430 string mainTmp("/tmp");
431 int t(vector<char *> const & arg)
434 cerr << "lyxclient: The option -t requires 1 argument."
442 string serverPid; // Init to empty string
443 int p(vector<char *> const & arg)
446 cerr << "lyxclient: The option -p requires 1 argument."
454 } // namespace cmdline
456 using support::prefixIs;
458 int main(int argc, char * argv[])
460 CmdLineParser parser;
461 parser.helper["-h"] = cmdline::h;
462 parser.helper["-c"] = cmdline::c;
463 parser.helper["-g"] = cmdline::g;
464 parser.helper["-n"] = cmdline::n;
465 parser.helper["-a"] = cmdline::a;
466 parser.helper["-t"] = cmdline::t;
467 parser.helper["-p"] = cmdline::p;
468 // Command line failure conditions:
469 if((!parser.parse(argc, argv))
470 || (parser.isset["-c"] && parser.isset["-g"])
471 || (parser.isset["-a"] && parser.isset["-p"])) {
476 LyXDataSocket * server;
478 if(parser.isset["-a"]) {
479 server = new LyXDataSocket(cmdline::serverAddress);
480 if(!server->connected()) {
481 cerr << "lyxclient: " << "Could not connect to "
482 << cmdline::serverAddress << endl;
486 // We have to look for an address.
487 // serverPid can be empty.
488 vector<string> addrs = support::lyxSockets(cmdline::mainTmp, cmdline::serverPid);
489 vector<string>::iterator addr = addrs.begin();
490 vector<string>::iterator end = addrs.end();
492 server = new LyXDataSocket(*addr);
493 if(server->connected()) break;
494 cerr << "lyxclient: " << "Could not connect to "
500 cerr << "lyxclient: No suitable server found." << endl;
503 cerr << "lyxclient: " << "Connected to " << *addr << endl;
506 int const serverfd = server->fd();
509 iowatch.addfd(serverfd);
511 // Used to read from server
515 server->writeln("HELLO:" + cmdline::clientName);
516 // wait at most 2 seconds until server responds
518 if(iowatch.isset(serverfd) && server->readln(answer)) {
519 if(prefixIs(answer, "BYE:")) {
520 cerr << "lyxclient: Server disconnected." << endl;
521 cout << answer << endl;
525 cerr << "lyxclient: No answer from server." << endl;
529 if(parser.isset["-g"] || parser.isset["-c"]) {
530 server->writeln(cmdline::singleCommand);
532 if(iowatch.isset(serverfd) && server->readln(answer)) {
534 if(prefixIs(answer, "ERROR:")) return 1;
537 cerr << "lyxclient: No answer from server." << endl;
542 // Take commands from stdin
543 iowatch.addfd(0); // stdin
544 bool saidbye = false;
545 while((!saidbye) && server->connected()) {
547 if(iowatch.isset(0)) {
550 if(command == "BYE:") {
551 server->writeln("BYE:");
554 server->writeln("LYXCMD:" + command);
557 if(iowatch.isset(serverfd)) {
558 while(server->readln(answer))
559 cout << answer << endl;