File: notionflux.c

package info (click to toggle)
notion 4.0.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 4,656 kB
  • sloc: ansic: 47,365; sh: 2,093; makefile: 594; perl: 270
file content (523 lines) | stat: -rw-r--r-- 12,415 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/* Copyright (C) 2019 The Notion development team

   This utility is part of the notion window manager, but uses a different
   license because GNU readline requires it.

   notionflux is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License (to be compatible with
   GNU readline) as well as Lesser General Public License (to be more compatible
   with notion itself) as published by the Free Software Foundation, either
   version 2 of the Licenses, or (at your option) any later version.

   By linking against readline, the created binary will be subject to the terms
   of GPL version 3.

   notionflux is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with notionflux.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <X11/Xlib.h>
#include <X11/Xatom.h>

#include <readline/readline.h>
#include <readline/history.h>

#include <lua.h>
#include <lauxlib.h>

#include "../notionflux.h"

#ifndef LUA_OK
#define LUA_OK 0
#endif

#define die(...) fprintf(stderr, __VA_ARGS__), exit(1)

#define SOCK_ATOM "_NOTION_MOD_NOTIONFLUX_SOCKET"

char const *sockfilename = NULL;
char const *histfile = NULL;

char const *get_socket_filename(void)
{
	Display *dpy = XOpenDisplay(NULL);
	if (!dpy)
		die("Failed to open display\n");

	Window root = DefaultRootWindow(dpy);
	Atom sockname_prop = XInternAtom(dpy, SOCK_ATOM, True);
	if (sockname_prop == None)
		die("No %s property set on the root window... is notion "
		    "running with mod_notionflux loaded?\n", SOCK_ATOM);

	Atom type;
	int d1; /* dummy */
	unsigned long d2, d3; /* dummy */
	unsigned char *ret;
	int pr = XGetWindowProperty(dpy, root, sockname_prop, 0L, 512L, False,
				    XA_STRING, &type, &d1, &d2, &d3, &ret);

	if (pr != Success || type != XA_STRING)
		 die("XGetWindowProperty failed\n");

	char *rv = strdup((char*)ret);

	XFree(ret);
	XCloseDisplay(dpy);
	return rv;
}

/* Send file descriptors over a unix domain socket.
   See unix(4), unix(7), sendmsg(2), cmsg(3) */
bool unix_send_fds(int unix, int fd) {
	/* yay for boilerplate */
	struct msghdr msg = {0};
	struct cmsghdr *cmsg;
	unsigned char iov_buf[4] = {23, 42, 128, 7}; /* our magic number, I guess */
	struct iovec io = {.iov_base = &iov_buf, .iov_len = sizeof(iov_buf)};
	union { /* something smart about alignment */
		char buf[CMSG_SPACE(sizeof(fd))];
		struct cmsghdr align;
	} u;
	msg.msg_iov = &io;
	msg.msg_iovlen = 1;
	msg.msg_control = &u.buf;
	msg.msg_controllen = sizeof(u.buf);
	cmsg = CMSG_FIRSTHDR(&msg);
	cmsg->cmsg_level = SOL_SOCKET;
	cmsg->cmsg_type = SCM_RIGHTS;
	cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
	memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
	if (sendmsg(unix, &msg, 0) == -1)
		return false;
	return true;
}

bool notion_restarted(void)
{
	char const *newsock = get_socket_filename();
	bool ret = strcmp(sockfilename, newsock) != 0;
	free((void*)sockfilename);
	sockfilename = newsock;
	return ret;
}

FILE *sock_connect(void)
{
	struct sockaddr_un serv;
	if (strlen(sockfilename) >= sizeof(serv.sun_path))
		die("Socket file name too long\n");
	int sock = socket(AF_UNIX, SOCK_STREAM, 0);

	serv.sun_family = AF_UNIX;
	strcpy(serv.sun_path, sockfilename);
	if (connect(sock, (struct sockaddr*)&serv, sizeof(serv)) == -1) {
		if (notion_restarted()) {
			fputs("Notion was restarted, connecting to new instance.\n", stderr);
			return sock_connect();
		} else {
			die("Failed to connect to socket %s\n", sockfilename);
		}
	}

	if (!unix_send_fds(sock, STDOUT_FILENO)) /* used for lua's print() */
		die("Failed to send stdout to notion.\n");

	FILE *f = fdopen(sock, "w+");
	if (!f)
		die("fdopen failed\n");

	return f;
}

/* read from f until EOF */
size_t slurp(FILE *f, char *buf, size_t n)
{
	size_t bytes = fread(buf, 1, n-1, f);
	buf[bytes]='\0';
	return bytes+1;
}

FILE *request(char const buf[MAX_DATA], char *type)
{
	FILE *sock = NULL;

	sock = sock_connect();

	fputs(buf, sock);
	fputc('\0', sock);
	fflush(sock);

	fread(type, 1, 1, sock);

	if (feof(sock) || ferror(sock))
		die("Short response from mod_notionflux.\n");

	if (*type != 'S' && *type != 'E')
		die("Unknown response type (%x)\n", (int)*type);

	return sock;
}

bool response(char buf[MAX_DATA], FILE **sock)
{
	if (!*sock)
		return false;

	size_t bytes = slurp(*sock, buf, MAX_DATA);
	if (bytes == MAX_DATA)
		return true;

	if (ferror(*sock))
		die("Error condition on mod_notionflux response.\n");

	/* must be feof */
	fclose(*sock);
	*sock = NULL;
	return true;
}

struct buf {
	size_t size;
	char *cur;
	char buf[MAX_DATA];
};

size_t buf_pos(struct buf *buf)
{
	return buf->cur - buf->buf;
}

bool buf_append(struct buf *buf, char const *str)
{
	size_t len = strlen(str);

	if (buf_pos(buf) + len >= buf->size)
		return false;

	memcpy(buf->cur, str, len + 1);
	buf->cur += len;
	return true;
}

void buf_grow(struct buf **buf, size_t n)
{
	size_t bufsize = (*buf)->size + n;
	size_t structsize = bufsize + (sizeof(struct buf) - sizeof((*buf)->buf));
	size_t pos = buf_pos(*buf);
	*buf = realloc(*buf, structsize);
	if (!*buf)
		die("realloc failed\n");
	(*buf)->size = bufsize;
	(*buf)->cur = (*buf)->buf + pos;
}

void *alloc(size_t bytes)
{
	void *buf = malloc(bytes);
	if (!buf)
		die("malloc failed\n");
	return buf;
}

struct buf *buf_make(void)
{
	struct buf *buf = alloc(sizeof(*buf));
	buf->cur = buf->buf;
	buf->buf[0] = 0;
	buf->size = MAX_DATA;
	return buf;
}

char *completion_generator(const char *text, int state)
{
	static struct buf *buf = NULL;
	const char *req_str = "return table.concat("
		"mod_query.do_complete_lua(_G,'%s'),' ');";
	rl_completion_suppress_append = 1;

	if (state == 0) {
		if (buf) free(buf); /* huh */
		buf = buf_make();

		char temp[MAX_DATA];
		snprintf(temp, MAX_DATA, req_str, text);

		char type;
		FILE *remote = request(temp, &type);
		if (type == 'E') {
			fclose(remote);
			goto finish;
		}

		while (response(temp, &remote)) {
			if (!buf_append(buf, temp)) {
				buf_grow(&buf, MAX_DATA);
				buf_append(buf, temp);
			}
		}
		buf->cur = buf->buf;
	}

	char const skip_chars[] = " \"\n\r";
	buf->cur += strspn(buf->cur, skip_chars);

	if (*buf->cur == '\0')
		goto finish;

	size_t length = strcspn(buf->cur, skip_chars);
	buf->cur[length] = '\0';

	char *ret;
	char *lastdot = strrchr(text, '.');
	char *lastcolon = strrchr(text, ':');
	lastdot = lastcolon && lastdot < lastcolon ? lastcolon : lastdot;
	if (!lastdot) {
		ret = strdup(buf->cur);
	} else {
		/* mod_query trims tables in completions, prepend back */
		size_t dotpos = lastdot - text + 1;
		ret = alloc(dotpos + length + 1);
		ret[0] = '\0';
		strncat(ret, text, dotpos);
		strcat(ret, buf->cur);
	}

	buf->cur += length+1;
	return ret;
finish:
	free(buf);
	buf = NULL;
	return NULL;
}

int initialize_readline(void)
{
	rl_readline_name = "notionflux";
	rl_completion_entry_function = completion_generator;
	rl_basic_word_break_characters = " \t\n#;|&{(["
		"<>~="
		"+-*/%^";
	rl_basic_quote_characters = "\'\"";
	return 0;
}

void read_histfile(void)
{
	char *home = getenv("HOME");
	if (!home) {
		fputs("$HOME is not set, can't find history file.\n", stderr);
		return;
	}

	char fname[4096];
	snprintf(fname, sizeof(fname), "%s/.notion/notionflux.hist", home);
	histfile = strdup(fname);

	int err = read_history(fname);
	if (err != 0 && err != ENOENT)
		fprintf(stderr, "Error reading history file: %s.\n", strerror(err));
}

void save_histfile(void)
{
	if (histfile && strlen(histfile) > 0) {
		int err = write_history(histfile);
		if (err != 0)
			fprintf(stderr, "Error writing history: %s.\n", strerror(err));
	}
}


struct buf input = {MAX_DATA, input.buf, {0}};

#if 1 /* Ideas taken from lua/lua.c, because the REPL isn't part of liblua */

/* mark in error messages for incomplete statements */
#define EOFMARK		"<eof>"
#define marklen		(sizeof(EOFMARK)/sizeof(char) - 1)

bool is_lua_incomplete(lua_State *L, char const *lua, size_t len)
{
	lua_settop(L, 0);
	int status = luaL_loadbuffer(L, lua, len, "=stdin");

	if (status == LUA_ERRSYNTAX) {
		size_t lmsg;
		const char *msg = lua_tolstring(L, -1, &lmsg);
		if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) {
			lua_pop(L, 1);
			return true;
		}
	}
	return false;
}

char const *make_lua_exp(char *lua, size_t size)
{
	static lua_State *L = NULL;
	if (!L) L=luaL_newstate();

	lua_settop(L, 0);

	/* Inspired by Lua 5.3:
	 * Attempt to add a return keyword and see if the snippet can be loaded
	 * without an error (which would mean that it is an expression). If not,
	 * see if it is complete. If it isn't complete either, wait for the user
	 * to finish the statement. This way, the user doesn't have to type
	 * return in front of everything and still gets to see the return value. */

	const char *retline = lua_pushfstring(L, "return %s;", lua);
	int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin");

	if (status == LUA_OK)
		return retline; /* managed by Lua's GC */
	else if (!is_lua_incomplete(L, lua, size))
		return lua;
	return NULL;
}
#endif

#define input_append(str) buf_append(&input, str)
#define input_reset() prompt="lua> ", input.cur=input.buf, input.buf[0]=0

int repl_main(void)
{
	char *line = NULL;
	char const *prompt;
	rl_startup_hook = initialize_readline;
	input_reset();

	read_histfile();
	while (1) {
		free(line);
		line = readline(prompt);

		if (!line) { /* EOF */
			puts("^D");
			if (buf_pos(&input) == 0) {      /* user quit */
				return 0;
			} else {                /* abort previous input */
				input_reset();
				continue;
			}
		}

		if (line[0] == '\0') /* empty line, skip */
			continue;

		add_history(line);

		if (!input_append(line) || !input_append("\n")) {
			printf("Maximum length (%db) exceeded.\n", MAX_DATA);
			input_reset();
			continue;
		}

		char const *lua_exp = make_lua_exp(input.buf, buf_pos(&input));
		if (!lua_exp) {
			prompt = "...> ";
			continue;
		}

		char type = 0;
		FILE *remote = request(lua_exp, &type);
		char out[MAX_DATA];
		while (response(out, &remote))
			fputs(out, stdout);
		input_reset();
	}
	/* unreachable */
}

char const *make_dofile_exp(char const *path, struct buf *buf)
{
	char rpath[PATH_MAX];
	if (!realpath(path, rpath))
		die("Failed to resolve path: %s\n", strerror(errno));

	FILE *f = fopen(rpath, "r");
	if (!f)
		die("Failed to open file for reading: %s.\n", strerror(errno));
	fclose(f);

	buf_append(buf, "return dofile('");

	/* quote the string for lua */
	for (char *p=rpath; *p!='\0' && buf_pos(buf) < buf->size; p++){
		switch (*p) {
		case '\r': buf_append(buf, "\\r"); continue;
		case '\n': buf_append(buf, "\\n"); continue;
		case '\t': buf_append(buf, "\\t"); continue;
		case '\'': buf_append(buf, "\\'"); continue;
		case '\f': buf_append(buf, "\\f"); continue;
		case '\v': buf_append(buf, "\\v"); continue;
		case '\\': buf_append(buf, "\\\\"); continue;
		}

		if (*p >= ' ' && *p <= '~') { /* printable 7-bit ASCII */
			char b[] = {*p, '\0'};
			buf_append(buf, b);
		} else {
			char b[6] = {0};
			snprintf(b, sizeof(b), "\\%d", *p);
			buf_append(buf, b);
		}
	}

	if (!buf_append(buf, "');--"))
		die("Filename too long.\n");

	buf->cur = buf->buf;
	return buf->buf;
}

int main(int argc, char **argv)
{
	sockfilename = get_socket_filename();
	struct buf buf = {MAX_DATA, buf.buf, {0}};
	char const *data;

	if (argc == 1 && isatty(STDIN_FILENO)) {
		atexit(save_histfile);
		return repl_main();
	} else if (argc == 1 || (argc == 2 && strcmp(argv[1], "-R") == 0)) {
		data = buf.buf;
		slurp(stdin, buf.buf, buf.size);
	} else if (argc == 2 && argv[1][0] != '-') {
		data = make_dofile_exp(argv[1], &buf);
	} else if (argc == 3 && strcmp(argv[1], "-e") == 0) {
		data = argv[2];
		if (strlen(data) > MAX_DATA)
			die("Too much data\n");
	} else {
		die("Usage: %s [-R|-e code|filename]\n", argv[0]);
	}

	FILE *remote;
	char type;
	remote = request(data, &type);

	FILE *dest = type == 'S' ? stdout : stderr;
	while (response(buf.buf, &remote))
		fputs(buf.buf, dest);

	return 0;
}