summaryrefslogtreecommitdiff
path: root/replay.c
blob: 3a40e16c9cec3fe0dac92342f239e22182f7297d (plain)
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
/*
 * This file is part of blabouncer (https://www.blatech.co.uk/l_bratch/blabouncer).
 * Copyright (C) 2019 Luke Bratch <luke@bratch.co.uk>.
 *
 * Blabouncer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3.
 *
 * Blabouncer 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 blabouncer. If not, see <http://www.gnu.org/licenses/>.
*/

#include "replay.h"

// Return the unixtime timestamp at the start of a line,
// or -1 if a timestamp couldn't be extracted
int gettimestamp(char *str) {
  int timestamp;
  char timestr[TIMELEN];
  int count = 0;

  // Make sure we're starting with a digit
  if (!isdigit(str[0])) {
    return -1;
  }

  // Extract each digit until we encounter a non-digit
  for (int i = 0; i < TIMELEN; i++) {
    if (isdigit(str[i])) {
      timestr[count] = str[i];
      count++;
    }
  }

  timestr[count] = '\0'; // Null terminate

  timestamp = strtol(timestr, NULL, 10); // Convert resulting string to an integer, base 10

  return timestamp;
}

// Set 'str' to a string with the leading unixtime timestamp removed.
// Returns 1 on success, 0 on failure
int striptimestamp(char *str) {
  char line[MAXCHAR];
  int count = 0;

  // Make sure we're starting with a digit
  if (!isdigit(str[0])) {
    return 0;
  }

  // Skip over each digit until we encounter a non-digit, record the position
  for (int i = 0; i < TIMELEN; i++) {
    if (isdigit(str[i])) {
      count++;
    }
  }

  // Skip over the space
  count++;

  int count2 = 0;

  // Copy from the end of the digits (and the space) until the end of the string
  for (size_t i = count; i < strlen(str); i++) {
    line[count2] = str[i];
    count2++;
  }

  strncpy(str, line, count2);
  str[count2] = '\0';

  return 1;
}

// Take a string like:
// 1557592901 :foo!bar@baz PRIVMSG foo :hello world
// And convert it to:
// :foo!bar@baz PRIVMSG foo :[17:41:41] hello world
// Only inserts the formatted time for PRIVMSGs at the moment (and maybe only needs to!).
void formattime(char *str) {
  // Extract the timestamp for conversion into [HH:MM:SS]
  char timestr[TIMELEN];
  sprintf(timestr, "%d", gettimestamp(str)); // Convert int time to string time
  struct tm tm;
  strptime(timestr, "%s", &tm);
  char timestampf[TIMELEN]; // Formatted timestamp
  // Convert into [HH:MM:SS]
  strftime(timestampf, TIMELEN, "[%H:%M:%S]", &tm);

  // Strip the original unixtimestamp
  striptimestamp(str);

  // Take note of the length
  int len = strlen(str);

  // Find the start of the message if it's a PRIVMSG
  char *ret;
  int pos1;
  if ((ret = strstr(str, "PRIVMSG")) != NULL) {
    // Position within str of "PRIVMSG"
    pos1 = ret - str;
  } else {
    // If it's not a PRIVMSG, stop here
    return;
  }

  char *ret2;
  int pos2;
  // Find the start of the actual message within the PRIVMSG
  // TODO - What if it's some other message with a colon in it?  Find PRIVMSG or not properly.
  if ((ret2 = strstr(ret, ":")) != NULL) {
    // Position within ret of ":"
    pos2 = ret2 - ret;
  } else {
    // Didn't find the real message, weird.
    return;
  }

  // Position of start of PRIVMSG colon in original string
  int realpos = pos1 + pos2 + 1;

  // Build the new formatted string
  char newline[MAXCHAR];

  // First bit (:foo!bar@baz PRIVMSG foo :)
  for (int i = 0; i < realpos; i++) {
    newline[i] = str[i];
  }

  // Second bit (:foo!bar@baz PRIVMSG foo :[HH:MM:SS])
  int j = 0;
  for (int i = realpos; i < TIMELEN + realpos - 1; i++) { // -1 to avoid the null char from timestampf
    newline[i] = timestampf[j];
    j++;
  }

  // Insert a space after the formatted timestamp
  newline[TIMELEN + realpos - 1] = ' ';

  // Final bit (the original PRIVMSG contents)
  for (int i = TIMELEN + realpos; i < len + TIMELEN; i++) {
    newline[i] = str[i - TIMELEN];
  }

  // Copy the whole thing back to str and null terminate
  strncpy(str, newline, len + TIMELEN);
  str[len + TIMELEN] = '\0';
}

// Return the number of lines in the replay log since 'seconds' seconds ago, or -1 if there a problem.
// 'basedir' is the directory in which to find 'replay.log'.
int replaylines(int seconds, char *basedir) {
  FILE *fp;
  char str[MAXCHAR];
  char filename[PATH_MAX];

  // Build path
  snprintf(filename, PATH_MAX, "%s/replay.log", basedir);

  int numlines = 0;

  fp = fopen(filename, "r");

  if (fp == NULL) {
    printf("error: could not open replay log '%s'.\n", filename);
    // Assume the file just doesn't exist yet - TODO - Interpret error codes to see what happened.
    fclose(fp);
    return 0;
  }

  // Get the current time for comparison later
  int timenow = (int)time(NULL);

  while (fgets(str, MAXCHAR, fp) != NULL) {
    // Read the timestamp from each line
    int timestamp = gettimestamp(str);
    if (timestamp < 1) {
      printf("Error reading timestamp from replay log file.\n");
      fclose(fp);
      return -1;
    }
    
    // If the line is within range of the requested time, count it
    if (timestamp >= timenow - seconds) {
      numlines++;
    }
  }

  fclose(fp);
  return numlines;
}

// Set 'str' to the line in the log with a timestamp of greater than 'seconds'
// seconds ago, plus however many lines 'linenum' is set to.  'basedir' is the
// directory in which to find 'replay.log'.
// Also modify the line to include a timestamp in the form "[HH:MM:SS]".
// Returns 1 on success, or 0 on failure.
// TODO - This is horribly inefficient since it re-reads the entire file each call, rewrite this!
int readreplayline(int seconds, int linenum, char *str, char *basedir) {
  FILE *fp;
  char line[MAXCHAR];
  char filename[PATH_MAX];

  // Build path
  snprintf(filename, PATH_MAX, "%s/replay.log", basedir);

  int count = 0;

  fp = fopen(filename, "r");

  if (fp == NULL) {
    debugprint(DEBUG_CRIT, "error: readreplayline(): could not open replay log '%s'.\n", filename);
    fclose(fp);
    return 0;
  }

  // Get the current time for comparison later
  int timenow = (int)time(NULL);

  while (fgets(line, MAXCHAR, fp) != NULL) {
    // Read the timestamp from each line
    int timestamp = gettimestamp(line);
    if (timestamp < 1) {
      debugprint(DEBUG_CRIT, "readreplayline(): Error reading timestamp from replay log file.\n");
      fclose(fp);
      return 0;
    }

    // If the line is within range of the requested time...
    if (timestamp >= timenow - seconds) {
      // ...and it is the current requested line then return it
      if (count == linenum) {
        // Insert our formatted [HH:MM:SS] timestamp into the message
        formattime(line);

        strncpy(str, line, strlen(line));
        str[strlen(line)] = '\0';
        fclose(fp);
        return 1;
      }
      count++;
    }
  }

  // If we got here something went wrong
  fclose(fp);
  return 0;
}

// Returns the number of seconds ago that 'nick' last spoke, or -1 if there is a problem.
// 'basedir' is the directory in which to find 'replay.log'.
int lastspokesecondsago(char *nick, char *basedir) {
  FILE *fp;
  char str[MAXCHAR];
  char filename[PATH_MAX];

  // Build path
  snprintf(filename, PATH_MAX, "%s/replay.log", basedir);

  int lastspoketime = 0; // When 'nick' last spoke

  // Get the current time for comparison later
  int timenow = (int)time(NULL);

  fp = fopen(filename, "r");

  if (fp == NULL) {
    printf("error: replaylineslastspoke(): could not open replay log '%s'.\n", filename);
    // Assume the file just doesn't exist yet - TODO - Interpret error codes to see what happened.
    fclose(fp);
    return 0;
  }

  while (fgets(str, MAXCHAR, fp) != NULL) {
    // Split the line up to determine if it was a PRIVMSG sent by the requested 'nick'
    // TODO - This may also be terribly inefficient

    // Copy to a temporary string
    char *strcopy = strdup(str);
    // Keep track of initial pointer for free()ing later
    char *strcopyPtr = strcopy;

    // Build array of each space-separated token, only need three (<timestamp> :<nick>!<user>@<host> PRIVMSG)
    char tokens[3][MAXDATASIZE + TIMELEN]; // Make IRC message length + our unix timestamp
    char *token;
    int counter = 0;
    for (int i = 0; i < 3; i++) {
      // Try to split
      if ((token = strsep(&strcopy, " ")) == NULL) {
        debugprint(DEBUG_CRIT, "replaylineslastspoke(): error splitting string on iteration '%d', returning -1!\n", i);
        return -1;
      }
      // Copy into the token array (strlen + 1 to get the NULL terminator)
      strncpy(tokens[i], token, strlen(token) + 1);
      counter++;
    }
    free(strcopyPtr);

    // Make sure there were at least three tokens
    if (counter < 3) {
      debugprint(DEBUG_CRIT, "replaylineslastspoke(): not enough tokens on line, only '%d', returning -1!\n", counter);
      return -1;
    }

    // Make sure it started with a valid timestamp
    int timestamp = gettimestamp(tokens[0]);
    if (timestamp < 0) {
      debugprint(DEBUG_CRIT, "replaylineslastspoke(): line didn't start with a timestamp, returning -1!\n", counter);
    }

    // Is it a PRIVMSG?
    if (strncmp(tokens[2], "PRIVMSG", strlen("PRIVMSG"))) {
      // Not a PRIVMSG, continue
      continue;
    }

    // Was it said by our 'nick'?
    extractnickfromprefix(tokens[1]);
    if (strncmp(tokens[1], nick, strlen(nick))) {
      // Not our 'nick', continue
      continue;
    }

    lastspoketime = timestamp;
  }

  fclose(fp);
  return timenow - lastspoketime;
}

// Write the line 'str' to the replay log file after prepending it with
// the current unixtime timestamp.  'basedir' is the directory in which
// to write to 'replay.log'.
// Expects a string in the format:
// :from!bar@baz PRIVMSG to :hello world
// With the ":foo!bar@baz "prefix being important.
// Returns 1 on success or 0 on failure.
int writereplayline(char *str, char *basedir) {
  FILE *fp;
  char line[MAXCHAR];
  char filename[PATH_MAX];

  // Build path
  snprintf(filename, PATH_MAX, "%s/replay.log", basedir);

  int bytes = 0;

  fp = fopen(filename, "a");

  if (fp == NULL) {
    debugprint(DEBUG_CRIT, "error: could not open replay log '%s' for writing.\n", filename);
    fclose(fp);
    return 0;
  }

  // Get the current time and manipulate it into a C string
  time_t timenow = time(NULL);
  int timenowlen = snprintf(NULL, 0, "%ld", timenow);
  char timenowstr[timenowlen + 1]; // TODO - Make this Year 2038 proof.
  snprintf(timenowstr, timenowlen + 1, "%ld", timenow);

  // Prepend the unixtime timestamp
  snprintf(line, MAXCHAR, "%s %s", timenowstr, str);

  // Ensure the line finishes with CRLF
  appendcrlf(line);

  debugprint(DEBUG_FULL, "Complete replay log string to write: '%s', length '%ld'.\n", line, strlen(line));

  // Write complete line to file
  if ((bytes = fprintf(fp, "%s", line)) < 0) {
    debugprint(DEBUG_CRIT, "error: could not write to replay log file.\n");
    fclose(fp);
    return 0;
  }

  fclose(fp);
  return bytes;
}