diff
minitox.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 66 insertions(+), 1 deletion(-)
diff --git a/minitox.c b/minitox.c
index cd8a85f..ab6a77f 100644
--- a/minitox.c
+++ b/minitox.c
@@ -392,7 +392,9 @@ struct termios saved_tattr;
struct AsyncREPL *async_repl;
void arepl_exit(void) {
- tcsetattr(NEW_STDIN_FILENO, TCSAFLUSH, &saved_tattr);
+ if (NEW_STDIN_FILENO >= 0) {
+ tcsetattr(NEW_STDIN_FILENO, TCSAFLUSH, &saved_tattr);
+ }
}
void setup_arepl(void) {
@@ -544,6 +546,67 @@ void arepl_reprint(struct AsyncREPL *arepl) {
fflush(stdout);
}
+static void free_chat_hist(struct ChatHist *hist) {
+ while (hist) {
+ struct ChatHist *next = hist->next;
+ free(hist->msg);
+ free(hist);
+ hist = next;
+ }
+}
+
+static void cleanup_on_exit(void) {
+ while (requests) {
+ struct Request *req = requests;
+ requests = req->next;
+ if (!req->is_friend_request) {
+ free(req->userdata.group.cookie);
+ }
+ free(req->msg);
+ free(req);
+ }
+
+ while (friends) {
+ struct Friend *f = friends;
+ friends = f->next;
+ free(f->name);
+ free(f->status_message);
+ free_chat_hist(f->hist);
+ free(f);
+ }
+
+ while (groups) {
+ struct Group *g = groups;
+ groups = g->next;
+ free(g->title);
+ free(g->peers);
+ free_chat_hist(g->hist);
+ free(g);
+ }
+
+ free(self.name);
+ self.name = NULL;
+ free(self.status_message);
+ self.status_message = NULL;
+
+ if (async_repl) {
+ free(async_repl->line);
+ free(async_repl->prompt);
+ free(async_repl);
+ async_repl = NULL;
+ }
+
+ if (tox) {
+ tox_kill(tox);
+ tox = NULL;
+ }
+
+ if (NEW_STDIN_FILENO >= 0 && NEW_STDIN_FILENO != STDIN_FILENO) {
+ close(NEW_STDIN_FILENO);
+ NEW_STDIN_FILENO = -1;
+ }
+}
+
#define _AREPL_CURSOR_LEFT() arepl->line[arepl->sz - (++arepl->nstack)] = arepl->line[--arepl->nbuf]
#define _AREPL_CURSOR_RIGHT() arepl->line[arepl->nbuf++] = arepl->line[arepl->sz - (arepl->nstack--)]
@@ -1453,6 +1516,8 @@ void repl_iterate(void){
int main(int argc, char **argv) {
+ atexit(cleanup_on_exit);
+
if (argc == 2 && strcmp(argv[1], "--help") == 0) {
fputs("Usage: minitox\n", stdout);
fputs("\n", stdout);