File: log.cpp

package info (click to toggle)
tinymux 2.10.1.14-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 6,212 kB
  • ctags: 8,535
  • sloc: cpp: 111,587; sh: 5,867; ansic: 141; makefile: 139
file content (685 lines) | stat: -rw-r--r-- 16,353 bytes parent folder | download | duplicates (2)
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
/*! \file log.cpp
 * \brief Logging routines.
 *
 * $Id: log.cpp 4459 2009-12-05 16:53:59Z brazilofmux $
 *
 */

#include "copyright.h"
#include "autoconf.h"
#include "config.h"
#include "externs.h"

#include "command.h"
#include "mathutil.h"

NAMETAB logdata_nametab[] =
{
    {T("flags"),           1,  0,  LOGOPT_FLAGS},
    {T("location"),        1,  0,  LOGOPT_LOC},
    {T("owner"),           1,  0,  LOGOPT_OWNER},
    {T("timestamp"),       1,  0,  LOGOPT_TIMESTAMP},
    {(UTF8 *) NULL,        0,  0,  0}
};

NAMETAB logoptions_nametab[] =
{
    {T("accounting"),      2,  0,  LOG_ACCOUNTING},
    {T("all_commands"),    2,  0,  LOG_ALLCOMMANDS},
    {T("bad_commands"),    2,  0,  LOG_BADCOMMANDS},
    {T("buffer_alloc"),    3,  0,  LOG_ALLOCATE},
    {T("bugs"),            3,  0,  LOG_BUGS},
    {T("checkpoints"),     2,  0,  LOG_DBSAVES},
    {T("config_changes"),  2,  0,  LOG_CONFIGMODS},
    {T("create"),          2,  0,  LOG_PCREATES},
    {T("killing"),         1,  0,  LOG_KILLS},
    {T("logins"),          1,  0,  LOG_LOGIN},
    {T("network"),         1,  0,  LOG_NET},
    {T("problems"),        1,  0,  LOG_PROBLEMS},
    {T("security"),        2,  0,  LOG_SECURITY},
    {T("shouts"),          2,  0,  LOG_SHOUTS},
    {T("startup"),         2,  0,  LOG_STARTUP},
    {T("suspect"),         2,  0,  LOG_SUSPECTCMDS},
    {T("time_usage"),      1,  0,  LOG_TIMEUSE},
    {T("wizard"),          1,  0,  LOG_WIZARD},
    {(UTF8 *) NULL,        0,  0,  0}
};

/* ---------------------------------------------------------------------------
 * start_log: see if it is OK to log something, and if so, start writing the
 * log entry.
 */

bool start_log(const UTF8 * primary, const UTF8 * secondary)
{
    mudstate.logging++;
    if (  1 <= mudstate.logging
       && mudstate.logging <= 2)
    {
        if (!mudstate.bStandAlone)
        {
            // Format the timestamp.
            //
            UTF8 buffer[256];
            buffer[0] = '\0';
            if (mudconf.log_info & LOGOPT_TIMESTAMP)
            {
                CLinearTimeAbsolute ltaNow;
                ltaNow.GetLocal();
                FIELDEDTIME ft;
                ltaNow.ReturnFields(&ft);
                mux_sprintf(buffer, sizeof(buffer),
                    T("%d.%02d%02d:%02d%02d%02d "), ft.iYear, ft.iMonth,
                    ft.iDayOfMonth, ft.iHour, ft.iMinute, ft.iSecond);
            }

            // Write the header to the log.
            //
            if (  secondary
               && *secondary)
            {
                Log.tinyprintf(T("%s%s %3s/%-5s: "), buffer, mudconf.mud_name,
                    primary, secondary);
            }
            else
            {
                Log.tinyprintf(T("%s%s %-9s: "), buffer, mudconf.mud_name,
                    primary);
            }
        }

        // If a recursive call, log it and return indicating no log.
        //
        if (mudstate.logging == 1)
        {
            return true;
        }
        Log.WriteString(T("Recursive logging request." ENDLINE));
    }
    mudstate.logging--;
    return false;
}

/* ---------------------------------------------------------------------------
 * end_log: Finish up writing a log entry
 */

void end_log(void)
{
    Log.WriteString((UTF8 *) ENDLINE);
    Log.Flush();
    mudstate.logging--;
}

/* ---------------------------------------------------------------------------
 * log_perror: Write perror message to the log
 */

void log_perror(const UTF8 * primary, const UTF8 * secondary,
    const UTF8 * extra, const UTF8 * failing_object)
{
    start_log(primary, secondary);
    if (extra && *extra)
    {
        log_text(T("("));
        log_text(extra);
        log_text(T(") "));
    }

    // <Failing_object text>: <strerror() text>
    //
    Log.WriteString(failing_object);
    Log.WriteString(T(": "));
    Log.WriteString(mux_strerror(errno));
#ifndef WIN32
    Log.WriteString((UTF8 *) ENDLINE);
#endif // !WIN32
    Log.Flush();
    mudstate.logging--;
}

/* ---------------------------------------------------------------------------
 * log_text, log_number: Write text or number to the log file.
 */

void log_text(const UTF8 * text)
{
    Log.WriteString(strip_color(text));
}

void log_number(int num)
{
    Log.WriteInteger(num);
}

void DCL_CDECL log_printf(__in_z const UTF8 * fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    UTF8 aTempBuffer[SIZEOF_LOG_BUFFER];
    size_t nString = mux_vsnprintf(aTempBuffer, SIZEOF_LOG_BUFFER, fmt, ap);
    va_end(ap);
    Log.WriteBuffer(nString, aTempBuffer);
}

/* ---------------------------------------------------------------------------
 * log_name: write the name, db number, and flags of an object to the log.
 * If the object does not own itself, append the name, db number, and flags
 * of the owner.
 */

void log_name(dbref target)
{
    if (mudstate.bStandAlone)
    {
        Log.tinyprintf(T("%s(#%d)"), PureName(target), target);
    }
    else
    {
        UTF8 *tp;

        if (mudconf.log_info & LOGOPT_FLAGS)
        {
            tp = unparse_object(GOD, target, false);
        }
        else
        {
            tp = unparse_object_numonly(target);
        }
        Log.WriteString(strip_color(tp));
        free_lbuf(tp);
        if (  (mudconf.log_info & LOGOPT_OWNER)
           && target != Owner(target))
        {
            if (mudconf.log_info & LOGOPT_FLAGS)
            {
                tp = unparse_object(GOD, Owner(target), false);
            }
            else
            {
                tp = unparse_object_numonly(Owner(target));
            }
            Log.tinyprintf(T("[%s]"), strip_color(tp));
            free_lbuf(tp);
        }
    }
}

/* ---------------------------------------------------------------------------
 * log_name_and_loc: Log both the name and location of an object
 */

void log_name_and_loc(dbref player)
{
    log_name(player);
    if (  (mudconf.log_info & LOGOPT_LOC)
       && Has_location(player))
    {
        log_text(T(" in "));
        log_name(Location(player));
    }
    return;
}

static const UTF8 *OBJTYP(dbref thing)
{
    if (!Good_dbref(thing))
    {
        return T("??OUT-OF-RANGE??");
    }
    switch (Typeof(thing))
    {
    case TYPE_PLAYER:
        return T("PLAYER");
    case TYPE_THING:
        return T("THING");
    case TYPE_ROOM:
        return T("ROOM");
    case TYPE_EXIT:
        return T("EXIT");
    case TYPE_GARBAGE:
        return T("GARBAGE");
    default:
        return T("??ILLEGAL??");
    }
}

void log_type_and_name(dbref thing)
{
    Log.tinyprintf(T("%s #%d(%s)"), OBJTYP(thing), thing,
        Good_obj(thing) ? PureName(thing) : T(""));
    return;
}

void do_log
(
    dbref executor,
    dbref caller,
    dbref enactor,
    int   eval,
    int   key,
    int   nargs,
    UTF8 *whichlog,
    UTF8 *logtext,
    const UTF8 *cargs[],
    int   ncargs
)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(key);
    UNUSED_PARAMETER(nargs);
    UNUSED_PARAMETER(cargs);
    UNUSED_PARAMETER(ncargs);

    bool bValid = true;

    // Strip the filename of all ANSI.
    //
    UTF8 *pFilename = strip_color(whichlog);

    // Restrict filename to a subdirectory to reduce the possibility
    // of a security hole.
    //
    UTF8 *temp_ptr = (UTF8 *) strrchr((char *) pFilename, '/');
    if (temp_ptr)
    {
        pFilename = ++temp_ptr;
    }
    temp_ptr = (UTF8 *) strrchr((char *) pFilename, '\\');
    if (temp_ptr)
    {
        pFilename = ++temp_ptr;
    }

    // Check for and disallow leading periods, empty strings
    // and filenames over 30 characters.
    //
    size_t n = strlen((char *) pFilename);
    if (  n == 0
       || 30 < n)
    {
        bValid = false;
    }
    else
    {
        unsigned int i;
        for (i = 0; i < n; i++)
        {
            if (!mux_isalnum(pFilename[i]))
            {
                bValid = false;
                break;
            }
        }
    }

    UTF8 *pFullName = NULL;
    const UTF8 *pMessage = T("");
    if (bValid)
    {
        pFullName = alloc_lbuf("do_log_filename");
        mux_sprintf(pFullName, LBUF_SIZE, T("logs/M-%s.log"), pFilename);

        // Strip the message of all ANSI.
        //
        pMessage = strip_color(logtext);

        // Check for and disallow empty messages.
        //
        if (pMessage[0] == '\0')
        {
            bValid = false;
        }
    }

    if (!bValid)
    {
        if (pFullName)
        {
            free_lbuf(pFullName);
        }
        notify(executor, T("Syntax: @log file=message"));
        return;
    }

    FILE *hFile;
    if (mux_fopen(&hFile, pFullName, T("r")))
    {
        fclose(hFile);
        if (mux_fopen(&hFile, pFullName, T("a")))
        {
            // Okay, at this point, the file exists.
            //
            free_lbuf(pFullName);
            mux_fprintf(hFile, T("%s" ENDLINE), pMessage);
            fclose(hFile);
            return;
        }
    }
    free_lbuf(pFullName);

    notify(executor, T("Not a valid log file."));
    return;
}

CLogFile Log;
void CLogFile::WriteInteger(int iNumber)
{
    UTF8 aTempBuffer[I32BUF_SIZE];
    size_t nTempBuffer = mux_ltoa(iNumber, aTempBuffer);
    WriteBuffer(nTempBuffer, aTempBuffer);
}

void CLogFile::WriteBuffer(size_t nString, const UTF8 * pString)
{
    if (!bEnabled)
    {
        return;
    }

#if defined(WINDOWS_THREADS)
    EnterCriticalSection(&csLog);
#endif // WINDOWS_THREADS

    while (nString > 0)
    {
        size_t nAvailable = SIZEOF_LOG_BUFFER - m_nBuffer;
        if (nAvailable == 0)
        {
            Flush();
            continue;
        }

        size_t nToMove = nAvailable;
        if (nString < nToMove)
        {
            nToMove = nString;
        }

        // Move nToMove bytes from pString to aBuffer+nBuffer
        //
        memcpy(m_aBuffer + m_nBuffer, pString, nToMove);
        pString += nToMove;
        nString -= nToMove;
        m_nBuffer += nToMove;
    }
    Flush();

#if defined(WINDOWS_THREADS)
    LeaveCriticalSection(&csLog);
#endif // WINDOWS_THREADS
}

void CLogFile::WriteString(const UTF8 * pString)
{
    size_t nString = strlen((char *) pString);
    WriteBuffer(nString, pString);
}

void DCL_CDECL CLogFile::tinyprintf(const UTF8 * fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    UTF8 aTempBuffer[SIZEOF_LOG_BUFFER];
    size_t nString = mux_vsnprintf(aTempBuffer, SIZEOF_LOG_BUFFER, fmt, ap);
    va_end(ap);
    WriteBuffer(nString, aTempBuffer);
}

static void MakeLogName
(
    const UTF8 *pBasename,
    const UTF8 *szPrefix,
    CLinearTimeAbsolute lta,
    UTF8 *szLogName,
    size_t nLogName
)
{
    UTF8 szTimeStamp[18];
    lta.ReturnUniqueString(szTimeStamp, sizeof(szTimeStamp));
    if (  pBasename
       && pBasename[0] != '\0')
    {
        mux_sprintf(szLogName, nLogName, T("%s/%s-%s.log"),
            pBasename, szPrefix, szTimeStamp);
    }
    else
    {
        mux_sprintf(szLogName, nLogName, T("%s-%s.log"), szPrefix, szTimeStamp);
    }
}

bool CLogFile::CreateLogFile(void)
{
    CloseLogFile();

    m_nSize = 0;

    bool bSuccess;
#if defined(WINDOWS_FILES)
    size_t nFilename;
    UTF16 *pFilename = ConvertFromUTF8ToUTF16(m_szFilename, &nFilename);
    if (NULL == pFilename)
    {
        return false;
    }

    m_hFile = CreateFile(pFilename, GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ, 0, CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL + FILE_FLAG_SEQUENTIAL_SCAN, NULL);
    bSuccess = (INVALID_HANDLE_VALUE != m_hFile);
#elif defined(UNIX_FILES)
    bSuccess = mux_open(&m_fdFile, m_szFilename,
        O_RDWR | O_BINARY | O_CREAT | O_TRUNC);
#endif // UNIX_FILES
    return bSuccess;
}

void CLogFile::AppendLogFile(void)
{
    CloseLogFile();

    bool bSuccess;
#if defined(WINDOWS_FILES)
    size_t nFilename;
    UTF16 *pFilename = ConvertFromUTF8ToUTF16(m_szFilename, &nFilename);
    if (NULL == pFilename)
    {
        return;
    }

    m_hFile = CreateFile(pFilename, GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ, 0, OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL + FILE_FLAG_SEQUENTIAL_SCAN, NULL);
    bSuccess = (INVALID_HANDLE_VALUE != m_hFile);
#elif defined(UNIX_FILES)
    bSuccess = mux_open(&m_fdFile, m_szFilename, O_RDWR | O_BINARY);
#endif // UNIX_FILES

    if (bSuccess)
    {
#if defined(WINDOWS_FILES)
        SetFilePointer(m_hFile, 0, 0, FILE_END);
#elif defined(UNIX_FILES)
        mux_lseek(m_fdFile, 0, SEEK_END);
#endif // UNIX_FILES
    }
}

void CLogFile::CloseLogFile(void)
{
#if defined(WINDOWS_FILES)
    if (INVALID_HANDLE_VALUE != m_hFile)
    {
        CloseHandle(m_hFile);
        m_hFile = INVALID_HANDLE_VALUE;
    }
#elif defined(UNIX_FILES)
    if (MUX_OPEN_INVALID_HANDLE_VALUE != m_fdFile)
    {
        mux_close(m_fdFile);
        m_fdFile = MUX_OPEN_INVALID_HANDLE_VALUE;
    }
#endif // UNIX_FILES
}

#define FILE_SIZE_TRIGGER (512*1024UL)

void CLogFile::Flush(void)
{
    if (  m_nBuffer <= 0
       || !bEnabled)
    {
        return;
    }

    if (bUseStderr)
    {
        // There is no recourse if the following fails.
        //
        (void) fwrite(m_aBuffer, m_nBuffer, 1, stderr);
    }
    else
    {
        m_nSize += m_nBuffer;
#if defined(WINDOWS_FILES)
        unsigned long nWritten;
        bool fSuccess = true;
        if (!WriteFile(m_hFile, m_aBuffer, (DWORD) m_nBuffer, &nWritten, NULL))
        {
            fSuccess = false;
        }
#elif defined(UNIX_FILES)
        ssize_t written = mux_write(m_fdFile, m_aBuffer, m_nBuffer);
        bool fSuccess = (0 < written && m_nBuffer == (size_t) written);
#endif // UNIX_FILES

        if (!fSuccess)
        {
            raw_broadcast(WIZARD,
                T("GAME: Unable to write to the log.  The disk may be full."));
        }

        if (m_nSize > FILE_SIZE_TRIGGER)
        {
            CloseLogFile();

            m_ltaStarted.GetLocal();
            MakeLogName(m_pBasename, m_szPrefix, m_ltaStarted, m_szFilename,
                sizeof(m_szFilename));

            CreateLogFile();
        }
    }
    m_nBuffer = 0;
}

void CLogFile::SetPrefix(const UTF8 * szPrefix)
{
    if (  !bUseStderr
       && strcmp((char *) szPrefix, (char *) m_szPrefix) != 0)
    {
        if (bEnabled)
        {
            CloseLogFile();
        }

        UTF8 szNewName[SIZEOF_PATHNAME];
        MakeLogName(m_pBasename, szPrefix, m_ltaStarted, szNewName,
            sizeof(szNewName));
        if (bEnabled)
        {
            ReplaceFile(m_szFilename, szNewName);
        }
        mux_strncpy(m_szPrefix, szPrefix, sizeof(m_szPrefix)-1);
        mux_strncpy(m_szFilename, szNewName, sizeof(m_szFilename)-1);

        if (bEnabled)
        {
            AppendLogFile();
        }
    }
}

void CLogFile::SetBasename(const UTF8 * pBasename)
{
    if (m_pBasename)
    {
        MEMFREE(m_pBasename);
        m_pBasename = NULL;
    }

    if (  pBasename
       && strcmp((char *) pBasename, "-") == 0)
    {
        bUseStderr = true;
    }
    else
    {
        bUseStderr = false;
        if (pBasename)
        {
            m_pBasename = StringClone(pBasename);
        }
        else
        {
            m_pBasename = StringClone(T(""));
        }
    }
}

CLogFile::CLogFile(void)
{
#if defined(WINDOWS_THREADS)
    InitializeCriticalSection(&csLog);
#endif // WINDOWS_THREADS

    m_ltaStarted.GetLocal();
#if defined(WINDOWS_FILES)
    m_hFile = INVALID_HANDLE_VALUE;
#elif defined(UNIX_FILES)
    m_fdFile = MUX_OPEN_INVALID_HANDLE_VALUE;
#endif // UNIX_FILES
    m_nSize = 0;
    m_nBuffer = 0;
    bEnabled = false;
    bUseStderr = true;
    m_pBasename = NULL;
    m_szPrefix[0] = '\0';
    m_szFilename[0] = '\0';
}

void CLogFile::StartLogging()
{
    if (!bUseStderr)
    {
        m_ltaStarted.GetLocal();
        MakeLogName(m_pBasename, m_szPrefix, m_ltaStarted, m_szFilename,
            sizeof(m_szFilename));
        CreateLogFile();
    }
    bEnabled = true;
}

void CLogFile::StopLogging(void)
{
    Flush();
    bEnabled = false;
    if (!bUseStderr)
    {
        CloseLogFile();
        m_szPrefix[0] = '\0';
        m_szFilename[0] = '\0';
        SetBasename(NULL);
    }
}

CLogFile::~CLogFile(void)
{
    StopLogging();
#if defined(WINDOWS_THREADS)
    DeleteCriticalSection(&csLog);
#endif // WINDOWS_THREADS
}