cgi_error_disabled(): Use status code 403 and an appropriate response line
[privoxy.git] / w32log.c
1 const char w32log_rcs[] = "$Id: w32log.c,v 1.52 2016/07/28 00:38:47 ler762 Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/w32log.c,v $
5  *
6  * Purpose     :  Functions for creating and destroying the log window,
7  *                ouputting strings, processing messages and so on.
8  *
9  * Copyright   :  Written by and Copyright (C) 2001-2009 members of
10  *                the Privoxy team.  http://www.privoxy.org/
11  *
12  *                Written by and Copyright (C) 1999 Adam Lock
13  *                <locka@iol.ie>
14  *
15  *                This program is free software; you can redistribute it
16  *                and/or modify it under the terms of the GNU General
17  *                Public License as published by the Free Software
18  *                Foundation; either version 2 of the License, or (at
19  *                your option) any later version.
20  *
21  *                This program is distributed in the hope that it will
22  *                be useful, but WITHOUT ANY WARRANTY; without even the
23  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
24  *                PARTICULAR PURPOSE.  See the GNU General Public
25  *                License for more details.
26  *
27  *                The GNU General Public License should be included with
28  *                this file.  If not, you can view it at
29  *                http://www.gnu.org/copyleft/gpl.html
30  *                or write to the Free Software Foundation, Inc., 59
31  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
32  *
33  *********************************************************************/
34
35
36 #include "config.h"
37
38 #include <assert.h>
39 #include <stdio.h>
40
41 #ifndef STRICT
42 #define STRICT
43 #endif
44 #include <winsock2.h>
45 #include <windows.h>
46 #include <richedit.h>
47
48 #include "project.h"
49 #include "w32log.h"
50 #include "w32taskbar.h"
51 #include "win32.h"
52 #include "w32res.h"
53 #include "jcc.h"
54 #include "miscutil.h"
55 #include "errlog.h"
56 #include "loadcfg.h"
57
58 const char w32res_h_rcs[] = W32RES_H_VERSION;
59
60 const char w32log_h_rcs[] = W32LOG_H_VERSION;
61
62 #ifndef _WIN_CONSOLE /* entire file */
63
64 /*
65  * Timers and the various durations
66  */
67 #define TIMER_ANIM_ID               1
68 #define TIMER_ANIM_TIME             100
69 #define TIMER_ANIMSTOP_ID           2
70 #define TIMER_ANIMSTOP_TIME         1000
71 #define TIMER_CLIPBUFFER_ID         3
72 #define TIMER_CLIPBUFFER_TIME       1000
73 #define TIMER_CLIPBUFFER_FORCE_ID   4
74 #define TIMER_CLIPBUFFER_FORCE_TIME 5000
75
76 /*
77  * Styles of text that can be output
78  */
79 #define STYLE_NONE      0
80 #define STYLE_HIGHLIGHT 1
81 #define STYLE_LINK      2
82 #define STYLE_HEADER    3
83
84 /*
85  * Number of frames of animation in tray activity sequence
86  */
87 #define ANIM_FRAMES 8
88
89 #define DEFAULT_MAX_BUFFER_LINES    200
90 #define DEFAULT_LOG_FONT_NAME       "MS Sans Serif"
91 #define DEFAULT_LOG_FONT_SIZE       8
92
93 /*
94  * These values affect the way the log window behaves, they should be read
95  * from a file but for the moment, they are hardcoded here. Some options are
96  * configurable through the UI.
97  */
98
99 /* Indicates whether task bar shows activity animation */
100 BOOL g_bShowActivityAnimation = 1;
101
102 /* Indicates whether the log window is shown */
103 BOOL g_bShowLogWindow = 1;
104
105 /* Indicates if the log window appears on the task bar */
106 BOOL g_bShowOnTaskBar = 0;
107
108 /* Indicates whether closing the log window really just hides it */
109 BOOL g_bCloseHidesWindow = 1;
110
111 /* Indicates if messages are logged at all */
112 BOOL g_bLogMessages = 1;
113
114 /* Indicates whether log messages are highlighted */
115 BOOL g_bHighlightMessages = 1;
116
117 /* Indicates if buffer is limited in size */
118 BOOL g_bLimitBufferSize = 1;
119
120 /* Maximum number of lines allowed in buffer when limited */
121 int g_nMaxBufferLines = DEFAULT_MAX_BUFFER_LINES;
122
123 /* Font to use */
124 char g_szFontFaceName[32] = DEFAULT_LOG_FONT_NAME;
125
126 /* Size of font to use */
127 int g_nFontSize = DEFAULT_LOG_FONT_SIZE;
128
129
130 /* FIXME: this is a kludge */
131
132 const char * g_default_actions_file = NULL;
133 const char * g_user_actions_file = NULL;
134 const char * g_default_filterfile = NULL;
135 const char * g_user_filterfile = NULL;
136 #ifdef FEATURE_TRUST
137 const char * g_trustfile = NULL;
138 #endif /* def FEATURE_TRUST */
139
140 /* FIXME: end kludge */
141
142 /* Regular expression for detected URLs */
143 #define RE_URL "http:[^ \n\r]*"
144
145 /*
146  * Regular expressions that are used to perform highlight in the log window
147  */
148 static struct _Pattern
149 {
150    const char *str;
151    int style;
152    regex_t buffer;
153 } patterns_to_highlight[] =
154 {
155    /* url headers */
156    { RE_URL,                STYLE_LINK },
157 /* { "[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[^ \n\r]*", STYLE_LINK }, */
158    /* interesting text to highlight */
159    /*   see jcc.c crunch_reason for the full list */
160    { "Crunch: Blocked:",            STYLE_HIGHLIGHT },
161    { "Crunch: Untrusted",           STYLE_HIGHLIGHT },
162    { "Crunch: Redirected:",         STYLE_HIGHLIGHT },
163    { "Crunch: DNS failure",         STYLE_HIGHLIGHT },
164    { "Crunch: Forwarding failed",   STYLE_HIGHLIGHT },
165    { "Crunch: Connection failure",  STYLE_HIGHLIGHT },
166    { "Crunch: Out of memory",       STYLE_HIGHLIGHT },
167    { "Connect: Found reusable socket",     STYLE_HIGHLIGHT },
168    { "Connect: Reusing server socket",     STYLE_HIGHLIGHT },
169    { "Connect: Created new connection to", STYLE_HIGHLIGHT },
170    { "hung up on us",               STYLE_HIGHLIGHT },
171    { "Info: Loading actions file:", STYLE_HIGHLIGHT },
172    { "Info: Loading filter file:",  STYLE_HIGHLIGHT },
173    { "Info: Now toggled ",          STYLE_HIGHLIGHT },
174    { "Crunching Referer:",          STYLE_HIGHLIGHT },
175    /* what are all the possible error strings?? */
176    { "Error:",                      STYLE_HIGHLIGHT },
177    /* http headers */
178    { "referer:",            STYLE_HEADER },
179    { "proxy-connection:",   STYLE_HEADER },
180    { "proxy-agent:",        STYLE_HEADER },
181    { "user-agent:",         STYLE_HEADER },
182    { "host:",               STYLE_HEADER },
183    { "accept:",             STYLE_HEADER },
184    { "accept-encoding:",    STYLE_HEADER },
185    { "accept-language:",    STYLE_HEADER },
186    { "accept-charset:",     STYLE_HEADER },
187    { "accept-ranges:",      STYLE_HEADER },
188    { "date:",               STYLE_HEADER },
189    { "cache-control:",      STYLE_HEADER },
190    { "cache-last-checked:", STYLE_HEADER },
191    { "connection:",         STYLE_HEADER },
192    { "content-type",        STYLE_HEADER },
193    { "content-length",      STYLE_HEADER },
194    { "cookie",              STYLE_HEADER },
195    { "last-modified:",      STYLE_HEADER },
196    { "pragma:",             STYLE_HEADER },
197    { "server:",             STYLE_HEADER },
198    { "etag:",               STYLE_HEADER },
199    { "expires:",            STYLE_HEADER },
200    { "warning:",            STYLE_HEADER },
201    /* this is the terminator statement - do not delete! */
202    { NULL,                  STYLE_NONE }
203 };
204
205 /*
206  * Public variables
207  */
208 HWND g_hwndLogFrame;
209 HICON g_hiconApp;
210
211 /*
212  * Private variables
213  */
214 static CRITICAL_SECTION g_criticalsection;
215 static HWND g_hwndTray;
216 static HWND g_hwndLogBox;
217 static WNDPROC g_fnLogBox;
218 static HICON g_hiconAnim[ANIM_FRAMES];
219 static HICON g_hiconIdle;
220 static HICON g_hiconOff;
221 static int g_nAnimFrame;
222 static BOOL g_bClipPending = FALSE;
223 static int g_nRichEditVersion = 0;
224
225 /*
226  * Private functions
227  */
228 static HWND CreateLogWindow(HINSTANCE hInstance, int nCmdShow);
229 static HWND CreateHiddenLogOwnerWindow(HINSTANCE hInstance);
230 static LRESULT CALLBACK LogWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
231 static LRESULT CALLBACK LogOwnerWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
232 static LRESULT CALLBACK LogRichEditProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
233 static BOOL InitRichEdit(void);
234 static void LogClipBuffer(void);
235 static void LogCreatePatternMatchingBuffers(void);
236 static void LogDestroyPatternMatchingBuffers(void);
237 static int LogPutStringNoMatch(const char *pszText, int style);
238 static void SetIdleIcon(void);
239
240
241 /*********************************************************************
242  *
243  * Function    :  InitLogWindow
244  *
245  * Description :  Initialise the log window.
246  *
247  * Parameters  :  None
248  *
249  * Returns     :  Always TRUE (there should be error checking on the resources).
250  *
251  *********************************************************************/
252 BOOL InitLogWindow(void)
253 {
254    int i;
255
256    /* Load the icons */
257    g_hiconIdle = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_IDLE));
258    g_hiconOff  = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_OFF));
259    for (i = 0; i < ANIM_FRAMES; i++)
260    {
261       g_hiconAnim[i] = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_ANIMATED1 + i));
262    }
263    g_hiconApp = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_MAINICON));
264
265    /* Create the user interface */
266    g_hwndLogFrame = CreateLogWindow(g_hInstance, g_nCmdShow);
267    g_hwndTray = CreateTrayWindow(g_hInstance);
268    TrayAddIcon(g_hwndTray, 1, g_hiconApp, "Privoxy");
269
270    /* Create pattern matching buffers (for highlighting */
271    LogCreatePatternMatchingBuffers();
272
273    /* Create a critical section to protect multi-threaded access to certain things */
274    InitializeCriticalSection(&g_criticalsection);
275
276    return TRUE;
277
278 }
279
280
281 /*********************************************************************
282  *
283  * Function    :  TermLogWindow
284  *
285  * Description :  Cleanup the logwindow.
286  *
287  * Parameters  :  None
288  *
289  * Returns     :  N/A
290  *
291  *********************************************************************/
292 void TermLogWindow(void)
293 {
294    int i;
295
296    LogDestroyPatternMatchingBuffers();
297
298    TrayDeleteIcon(g_hwndTray, 1);
299    DeleteObject(g_hiconApp);
300    DeleteObject(g_hiconIdle);
301    DeleteObject(g_hiconOff);
302    for (i = 0; i < ANIM_FRAMES; i++)
303    {
304       DeleteObject(g_hiconAnim[i]);
305    }
306
307 }
308
309
310 /*********************************************************************
311  *
312  * Function    :  LogCreatePatternMatchingBuffers
313  *
314  * Description :  Compile the pattern matching buffers.
315  *
316  * Parameters  :  None
317  *
318  * Returns     :  N/A
319  *
320  *********************************************************************/
321 void LogCreatePatternMatchingBuffers(void)
322 {
323    int i;
324    for (i = 0; patterns_to_highlight[i].str != NULL; i++)
325    {
326       regcomp(&patterns_to_highlight[i].buffer, patterns_to_highlight[i].str, REG_ICASE);
327    }
328 }
329
330
331 /*********************************************************************
332  *
333  * Function    :  LogDestroyPatternMatchingBuffers
334  *
335  * Description :  Free up the pattern matching buffers.
336  *
337  * Parameters  :  None
338  *
339  * Returns     :  N/A
340  *
341  *********************************************************************/
342 void LogDestroyPatternMatchingBuffers(void)
343 {
344    int i;
345    for (i = 0; patterns_to_highlight[i].str != NULL; i++)
346    {
347       regfree(&patterns_to_highlight[i].buffer);
348    }
349 }
350
351
352 /*********************************************************************
353  *
354  * Function    :  LogPutString
355  *
356  * Description :  Inserts text into the logging window.  This is really
357  *                a regexp aware wrapper function to `LogPutStringNoMatch'.
358  *
359  * Parameters  :
360  *          1  :  pszText = pointer to string going to the log window
361  *
362  * Returns     :  1 => success, else the return code from `LogPutStringNoMatch'.
363  *                FIXME: this is backwards to the rest of IJB and to common
364  *                programming practice.  Please use 0 => success instead.
365  *
366  *********************************************************************/
367 int LogPutString(const char *pszText)
368 {
369    int i;
370    int result = 0;
371
372    if (!g_bLogMessages)
373    {
374       return 1;
375    }
376
377    if (pszText == NULL || strlen(pszText) == 0)
378    {
379       return 1;
380    }
381
382    /* Critical section stops multiple threads doing nasty interactions that
383     * foul up the highlighting and output.
384     */
385    EnterCriticalSection(&g_criticalsection);
386
387    if (g_bHighlightMessages)
388    {
389       regmatch_t match;
390
391       /* First things first, regexp scan for various things that we would like highlighted */
392       for (i = 0; patterns_to_highlight[i].str != NULL; i++)
393       {
394          if (regexec(&patterns_to_highlight[i].buffer, pszText, 1, &match, 0) == 0)
395          {
396             char *pszBefore = NULL;
397             char *pszMatch = NULL;
398             char *pszAfter = NULL;
399             int nMatchSize;
400
401             /* Split the string up into pieces representing the strings, before
402                at and after the matching pattern
403              */
404             if (match.rm_so > 0)
405             {
406                pszBefore = (char *)malloc((match.rm_so + 1) * sizeof(char));
407                memset(pszBefore, 0, (match.rm_so + 1) * sizeof(char));
408                strncpy(pszBefore, pszText, match.rm_so);
409             }
410             if (match.rm_eo < (regoff_t)strlen(pszText))
411             {
412                pszAfter = strdup(&pszText[match.rm_eo]);
413             }
414             nMatchSize = match.rm_eo - match.rm_so;
415             pszMatch = (char *)malloc(nMatchSize + 1);
416             strncpy(pszMatch, &pszText[match.rm_so], nMatchSize);
417             pszMatch[nMatchSize] = '\0';
418
419             /* Recursively call LogPutString */
420             if (pszBefore)
421             {
422                LogPutString(pszBefore);
423                free(pszBefore);
424             }
425             if (pszMatch)
426             {
427                LogPutStringNoMatch(pszMatch, patterns_to_highlight[i].style);
428                free(pszMatch);
429             }
430             if (pszAfter)
431             {
432                LogPutString(pszAfter);
433                free(pszAfter);
434             }
435
436             result = 1;
437             goto end;
438          }
439       }
440    }
441
442    result = LogPutStringNoMatch(pszText, STYLE_NONE);
443
444 end:
445    LeaveCriticalSection(&g_criticalsection);
446
447    return result;
448
449 }
450
451
452 /*********************************************************************
453  *
454  * Function    :  LogPutStringNoMatch
455  *
456  * Description :  Puts a string into the logging window.
457  *
458  * Parameters  :
459  *          1  :  pszText = pointer to string going to the log window
460  *          2  :  style = STYLE_NONE, STYLE_HEADER, STYLE_HIGHLIGHT, or STYLE_LINK
461  *
462  * Returns     :  Always 1 => success.
463  *                FIXME: this is backwards to the rest of IJB and to common
464  *                programming practice.  Please use 0 => success instead.
465  *
466  *********************************************************************/
467 int LogPutStringNoMatch(const char *pszText, int style)
468 {
469    CHARRANGE range;
470    CHARFORMAT format;
471    int nTextLength;
472
473    assert(g_hwndLogBox);
474    if (g_hwndLogBox == NULL)
475    {
476       return 1;
477    }
478
479    /* TODO preserve existing selection */
480
481    /* Go to the end of the text */
482    nTextLength = GetWindowTextLength(g_hwndLogBox);
483    range.cpMin = nTextLength;
484    range.cpMax = nTextLength;
485    SendMessage(g_hwndLogBox, EM_EXSETSEL, 0, (LPARAM) &range);
486
487    /* Apply a formatting style */
488    memset(&format, 0, sizeof(format));
489    format.cbSize = sizeof(format);
490    format.dwMask = CFM_BOLD | CFM_UNDERLINE | CFM_STRIKEOUT |
491       CFM_ITALIC | CFM_COLOR | CFM_FACE | CFM_SIZE | CFM_CHARSET;
492    format.bCharSet = DEFAULT_CHARSET;
493    format.yHeight = (g_nFontSize * 1440) / 72;
494    strlcpy(format.szFaceName, g_szFontFaceName, sizeof(format.szFaceName));
495    if (style == STYLE_NONE)
496    {
497       /* DO NOTHING */
498       format.dwEffects |= CFE_AUTOCOLOR;
499    }
500    else if (style == STYLE_HEADER)
501    {
502       format.dwEffects |= CFE_AUTOCOLOR | CFE_ITALIC;
503    }
504    else if (style == STYLE_HIGHLIGHT)
505    {
506       format.dwEffects |= CFE_AUTOCOLOR | CFE_BOLD;
507    }
508    else if (style == STYLE_LINK)
509    {
510       format.dwEffects |= CFE_UNDERLINE;
511       format.crTextColor = RGB(0, 0, 255);
512    }
513    SendMessage(g_hwndLogBox, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &format);
514
515    /* Append text to the end */
516    SendMessage(g_hwndLogBox, EM_REPLACESEL, FALSE, (LPARAM) pszText);
517
518    /* TODO Restore the old selection */
519
520    /* Purge buffer */
521    if (strchr(pszText, '\n') != NULL)
522    {
523       SetTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_ID, TIMER_CLIPBUFFER_TIME, NULL);
524       if (!g_bClipPending)
525       {
526          /* Set the force clip timer going. This timer ensures clipping is done
527             intermittently even when there is a sustained burst of logging
528          */
529          SetTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_FORCE_ID, TIMER_CLIPBUFFER_FORCE_TIME, NULL);
530       }
531       g_bClipPending = TRUE;
532    }
533
534    return 1;
535
536 }
537
538
539 /*********************************************************************
540  *
541  * Function    :  LogShowActivity
542  *
543  * Description :  Start the spinner.
544  *
545  * Parameters  :  None
546  *
547  * Returns     :  N/A
548  *
549  *********************************************************************/
550 void LogShowActivity(void)
551 {
552    /* Start some activity timers */
553    if (g_bShowActivityAnimation)
554    {
555       SetTimer(g_hwndLogFrame, TIMER_ANIM_ID, TIMER_ANIM_TIME, NULL);
556       SetTimer(g_hwndLogFrame, TIMER_ANIMSTOP_ID, TIMER_ANIMSTOP_TIME, NULL);
557    }
558
559 }
560
561
562 /*********************************************************************
563  *
564  * Function    :  LogClipBuffer
565  *
566  * Description :  Prunes old lines from the log.
567  *
568  * Parameters  :  None
569  *
570  * Returns     :  N/A
571  *
572  *********************************************************************/
573 void LogClipBuffer(void)
574 {
575    int nLines = SendMessage(g_hwndLogBox, EM_GETLINECOUNT, 0, 0);
576    if (g_bLimitBufferSize && nLines > g_nMaxBufferLines)
577    {
578       /* Compute the range representing the lines to be deleted */
579       LONG nLastLineToDelete = nLines - g_nMaxBufferLines;
580       LONG nLastChar = SendMessage(g_hwndLogBox, EM_LINEINDEX, nLastLineToDelete, 0);
581       CHARRANGE range;
582       range.cpMin = 0;
583       range.cpMax = nLastChar;
584
585       /* TODO get current selection */
586
587       /* TODO adjust and clip old selection against range to be deleted */
588
589       /* Select range and erase it (turning off autoscroll to prevent
590          nasty scrolling) */
591       SendMessage(g_hwndLogBox, EM_SETOPTIONS, ECOOP_XOR, ECO_AUTOVSCROLL);
592       SendMessage(g_hwndLogBox, EM_EXSETSEL, 0, (LPARAM) &range);
593       SendMessage(g_hwndLogBox, EM_REPLACESEL, FALSE, (LPARAM) "");
594       SendMessage(g_hwndLogBox, EM_SETOPTIONS, ECOOP_XOR, ECO_AUTOVSCROLL);
595
596       /* reposition (back to) the end of the log content */
597       range.cpMin = SendMessage (g_hwndLogBox, WM_GETTEXTLENGTH, 0, 0);
598       range.cpMax = -1;
599       SendMessage(g_hwndLogBox, EM_EXSETSEL, 0, (LPARAM) &range);
600
601       /* restore vertical ScrollBar stuff (messed up by AUTOVSCROLL) */
602       SendMessage (g_hwndLogBox, EM_SCROLL, SB_LINEDOWN, 0);
603
604    }
605
606 }
607
608
609 /*********************************************************************
610  *
611  * Function    :  CreateHiddenLogOwnerWindow
612  *
613  * Description :  Creates a hidden owner window that stops the log
614  *                window appearing in the task bar.
615  *
616  * Parameters  :
617  *          1  :  hInstance = application's instance handle
618  *
619  * Returns     :  Handle to newly created window.
620  *
621  *********************************************************************/
622 HWND CreateHiddenLogOwnerWindow(HINSTANCE hInstance)
623 {
624    static const char *szWndName = "PrivoxyLogOwner";
625    WNDCLASS wc;
626    HWND hwnd;
627
628    wc.style          = 0;
629    wc.lpfnWndProc    = LogOwnerWindowProc;
630    wc.cbClsExtra     = 0;
631    wc.cbWndExtra     = 0;
632    wc.hInstance      = hInstance;
633    wc.hIcon          = g_hiconApp;
634    wc.hCursor        = 0;
635    wc.hbrBackground  = 0;
636    wc.lpszMenuName   = 0;
637    wc.lpszClassName  = szWndName;
638
639    RegisterClass(&wc);
640
641    hwnd = CreateWindow(szWndName, szWndName,
642       WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
643       CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
644
645    return hwnd;
646
647 }
648
649
650 /*********************************************************************
651  *
652  * Function    :  LogOwnerWindowProc
653  *
654  * Description :  Dummy procedure that does nothing special.
655  *
656  * Parameters  :
657  *          1  :  hwnd = window handle
658  *          2  :  uMsg = message number
659  *          3  :  wParam = first param for this message
660  *          4  :  lParam = next param for this message
661  *
662  * Returns     :  Same as `DefWindowProc'.
663  *
664  *********************************************************************/
665 LRESULT CALLBACK LogOwnerWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
666 {
667    return DefWindowProc(hwnd, uMsg, wParam, lParam);
668
669 }
670
671
672 /*********************************************************************
673  *
674  * Function    :  CreateLogWindow
675  *
676  * Description :  Create the logging window.
677  *
678  * Parameters  :
679  *          1  :  hInstance = application's instance handle
680  *          2  :  nCmdShow = window show value (MIN, MAX, NORMAL, etc...)
681  *
682  * Returns     :  Handle to newly created window.
683  *
684  *********************************************************************/
685 HWND CreateLogWindow(HINSTANCE hInstance, int nCmdShow)
686 {
687    static const char *szWndName = "PrivoxyLogWindow";
688    static const char *szWndTitle = "Privoxy";
689
690    HWND hwnd = NULL;
691    HWND hwndOwner = (g_bShowOnTaskBar) ? NULL : CreateHiddenLogOwnerWindow(hInstance);
692    RECT rcClient;
693    WNDCLASSEX wc;
694
695    memset(&wc, 0, sizeof(wc));
696    wc.cbSize         = sizeof(wc);
697    wc.style          = CS_DBLCLKS;
698    wc.lpfnWndProc    = LogWindowProc;
699    wc.cbClsExtra     = 0;
700    wc.cbWndExtra     = 0;
701    wc.hInstance      = hInstance;
702    wc.hIcon          = g_hiconApp;
703    wc.hCursor        = 0;
704    wc.hbrBackground  = 0;
705    wc.lpszMenuName   = MAKEINTRESOURCE(IDR_LOGVIEW);
706    wc.lpszClassName  = szWndName;
707    wc.hbrBackground  = GetStockObject(WHITE_BRUSH);
708    RegisterClassEx(&wc);
709
710    hwnd = CreateWindowEx(WS_EX_APPWINDOW, szWndName, szWndTitle,
711       WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
712       CW_USEDEFAULT, hwndOwner, NULL, hInstance, NULL);
713
714    /* Now create a child list box */
715    GetClientRect(hwnd, &rcClient);
716
717    /* Create a rich edit control */
718    InitRichEdit();
719    g_hwndLogBox = CreateWindowEx(0, (g_nRichEditVersion == 0x0100) ? "RichEdit" : RICHEDIT_CLASS, "",
720       ES_AUTOVSCROLL | ES_MULTILINE | ES_READONLY | ES_NOHIDESEL | WS_CHILD | WS_VSCROLL | WS_HSCROLL | WS_VISIBLE,
721       rcClient.left, rcClient.top, rcClient.right, rcClient.bottom,
722       hwnd, NULL, hInstance, NULL);
723 /* SendMessage(g_hwndLogBox, EM_SETWORDWRAPMODE, 0, 0); */
724
725    /* Subclass the control to catch certain messages */
726    g_fnLogBox = (WNDPROC) GetWindowLongPtr(g_hwndLogBox, GWLP_WNDPROC);
727    SetWindowLongPtr(g_hwndLogBox, GWLP_WNDPROC, (LONG_PTR) LogRichEditProc);
728
729    /* Minimizing looks stupid when the log window is not on the task bar, so hide instead */
730    if (!g_bShowOnTaskBar &&
731          (nCmdShow == SW_SHOWMINIMIZED ||
732           nCmdShow == SW_MINIMIZE ||
733           nCmdShow == SW_SHOWMINNOACTIVE))
734    {
735       g_bShowLogWindow = FALSE;
736       nCmdShow = SW_HIDE;
737    }
738
739    ShowWindow(hwnd, nCmdShow);
740    UpdateWindow(hwnd);
741
742
743    GetClientRect(g_hwndLogFrame, &rcClient);
744    SetWindowPos(g_hwndLogBox, NULL, rcClient.left, rcClient.top, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top, SWP_NOZORDER);
745
746    return hwnd;
747
748 }
749
750
751 /*********************************************************************
752  *
753  * Function    :  InitRichEdit
754  *
755  * Description :  Initialise the rich edit control library.
756  *
757  * Parameters  :  None
758  *
759  * Returns     :  TRUE => success, FALSE => failure.
760  *                FIXME: this is backwards to the rest of IJB and to common
761  *                programming practice.  Please use 0 => success instead.
762  *
763  *********************************************************************/
764 BOOL InitRichEdit(void)
765 {
766    static HINSTANCE hInstRichEdit;
767    if (hInstRichEdit == NULL)
768    {
769       g_nRichEditVersion = 0;
770       hInstRichEdit = LoadLibraryA("RICHED20.DLL");
771       if (hInstRichEdit)
772       {
773          g_nRichEditVersion = _RICHEDIT_VER;
774       }
775       else
776       {
777          hInstRichEdit = LoadLibraryA("RICHED32.DLL");
778          if (hInstRichEdit)
779          {
780             g_nRichEditVersion = 0x0100;
781          }
782       }
783    }
784    return (hInstRichEdit != NULL) ? TRUE : FALSE;
785
786 }
787
788
789 /*********************************************************************
790  *
791  * Function    :  ShowLogWindow
792  *
793  * Description :  Shows or hides the log window.  We will also raise the
794  *                window on a show command in case it is buried.
795  *
796  * Parameters  :
797  *          1  :  bShow = TRUE to show, FALSE to mimize/hide
798  *
799  * Returns     :  N/A
800  *
801  *********************************************************************/
802 void ShowLogWindow(BOOL bShow)
803 {
804    if (bShow)
805    {
806       SetForegroundWindow(g_hwndLogFrame);
807       SetWindowPos(g_hwndLogFrame, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
808
809    }
810    else if (g_bShowOnTaskBar)
811    {
812       ShowWindow(g_hwndLogFrame, SW_MINIMIZE);
813    }
814    else
815    {
816       ShowWindow(g_hwndLogFrame, SW_HIDE);
817    }
818 }
819
820
821 /*********************************************************************
822  *
823  * Function    :  EditFile
824  *
825  * Description :  Opens the specified setting file for editing.
826  * FIXME: What if the file has no associated application. Check for return values
827 *        from ShellExecute??
828  *
829  * Parameters  :
830  *          1  :  filename = filename from the config (aka config.txt) file.
831  *
832  * Returns     :  N/A
833  *
834  *********************************************************************/
835 void EditFile(const char *filename)
836 {
837    if (filename)
838    {
839       ShellExecute(g_hwndLogFrame, "open", filename, NULL, NULL, SW_SHOWNORMAL);
840    }
841
842 }
843
844
845 /*--------------------------------------------------------------------------*/
846 /* Windows message handlers                                                 */
847 /*--------------------------------------------------------------------------*/
848
849
850 /*********************************************************************
851  *
852  * Function    :  OnLogRButtonUp
853  *
854  * Description :  Handler for WM_RBUTTONUP messages.
855  *
856  * Parameters  :
857  *          1  :  nModifier = wParam from mouse message (unused)
858  *          2  :  x = x coordinate of the mouse event
859  *          3  :  y = y coordinate of the mouse event
860  *
861  * Returns     :  N/A
862  *
863  *********************************************************************/
864 void OnLogRButtonUp(int nModifier, int x, int y)
865 {
866    HMENU hMenu = LoadMenu(g_hInstance, MAKEINTRESOURCE(IDR_POPUP_SELECTION));
867    if (hMenu != NULL)
868    {
869       HMENU hMenuPopup = GetSubMenu(hMenu, 0);
870
871       /* Check if there is a selection */
872       CHARRANGE range;
873       SendMessage(g_hwndLogBox, EM_EXGETSEL, 0, (LPARAM) &range);
874       if (range.cpMin == range.cpMax)
875       {
876          EnableMenuItem(hMenuPopup, ID_EDIT_COPY, MF_BYCOMMAND | MF_GRAYED);
877       }
878       else
879       {
880          EnableMenuItem(hMenuPopup, ID_EDIT_COPY, MF_BYCOMMAND | MF_ENABLED);
881       }
882
883       /* Display the popup */
884       TrackPopupMenu(hMenuPopup, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, x, y, 0, g_hwndLogFrame, NULL);
885       DestroyMenu(hMenu);
886    }
887
888 }
889
890
891 /*********************************************************************
892  *
893  * Function    :  OnLogCommand
894  *
895  * Description :  Handler for WM_COMMAND messages.
896  *
897  * Parameters  :
898  *          1  :  nCommand = the command portion of the menu selection event
899  *
900  * Returns     :  N/A
901  *
902  *********************************************************************/
903 void OnLogCommand(int nCommand)
904 {
905    switch (nCommand)
906    {
907       case ID_TOGGLE_SHOWWINDOW:
908          g_bShowLogWindow = !g_bShowLogWindow;
909
910          ShowLogWindow(g_bShowLogWindow);
911          break;
912
913       case ID_FILE_EXIT:
914          PostMessage(g_hwndLogFrame, WM_CLOSE, 0, 0);
915          break;
916
917       case ID_EDIT_COPY:
918          SendMessage(g_hwndLogBox, WM_COPY, 0, 0);
919          break;
920
921       case ID_VIEW_CLEARLOG:
922          SendMessage(g_hwndLogBox, WM_SETTEXT, 0, (LPARAM) "");
923          break;
924
925       case ID_VIEW_LOGMESSAGES:
926          g_bLogMessages = !g_bLogMessages;
927          /* SaveLogSettings(); */
928          break;
929
930       case ID_VIEW_MESSAGEHIGHLIGHTING:
931          g_bHighlightMessages = !g_bHighlightMessages;
932          /* SaveLogSettings(); */
933          break;
934
935       case ID_VIEW_LIMITBUFFERSIZE:
936          g_bLimitBufferSize = !g_bLimitBufferSize;
937          /* SaveLogSettings(); */
938          break;
939
940       case ID_VIEW_ACTIVITYANIMATION:
941          g_bShowActivityAnimation = !g_bShowActivityAnimation;
942          /* SaveLogSettings(); */
943          break;
944
945 #ifdef FEATURE_TOGGLE
946       case ID_TOGGLE_ENABLED:
947          global_toggle_state = !global_toggle_state;
948          log_error(LOG_LEVEL_INFO,
949             "Now toggled %s", global_toggle_state ? "ON" : "OFF");
950          /*
951           * Leverage TIMER_ANIMSTOP_ID to set the idle icon through the
952           * "application queue". According to MSDN, 10 milliseconds are
953           * the lowest value possible and seem to be close enough to
954           * "instantly".
955           */
956          SetTimer(g_hwndLogFrame, TIMER_ANIMSTOP_ID, 10, NULL);
957          break;
958 #endif /* def FEATURE_TOGGLE */
959
960       case ID_TOOLS_EDITCONFIG:
961          EditFile(configfile);
962          break;
963
964       case ID_TOOLS_EDITDEFAULTACTIONS:
965          EditFile(g_default_actions_file);
966          break;
967
968       case ID_TOOLS_EDITUSERACTIONS:
969          EditFile(g_user_actions_file);
970          break;
971
972       case ID_TOOLS_EDITDEFAULTFILTERS:
973          EditFile(g_default_filterfile);
974          break;
975
976       case ID_TOOLS_EDITUSERFILTERS:
977          EditFile(g_user_filterfile);
978          break;
979
980 #ifdef FEATURE_TRUST
981       case ID_TOOLS_EDITTRUST:
982          EditFile(g_trustfile);
983          break;
984 #endif /* def FEATURE_TRUST */
985
986       case ID_HELP_GPL:
987          ShellExecute(g_hwndLogFrame, "open", "LICENSE.txt", NULL, NULL, SW_SHOWNORMAL);
988          break;
989
990       case ID_HELP_FAQ:
991          ShellExecute(g_hwndLogFrame, "open", "doc\\faq\\index.html", NULL, NULL, SW_SHOWNORMAL);
992          break;
993
994       case ID_HELP_MANUAL:
995          ShellExecute(g_hwndLogFrame, "open", "doc\\user-manual\\index.html", NULL, NULL, SW_SHOWNORMAL);
996          break;
997
998       case ID_HELP_STATUS:
999          ShellExecute(g_hwndLogFrame, "open", CGI_PREFIX "show-status", NULL, NULL, SW_SHOWNORMAL);
1000          break;
1001
1002       case ID_HELP_ABOUT:
1003          MessageBox(g_hwndLogFrame, win32_blurb, "About Privoxy", MB_OK);
1004          break;
1005
1006       default:
1007          /* DO NOTHING */
1008          break;
1009    }
1010
1011 }
1012
1013
1014 /*********************************************************************
1015  *
1016  * Function    :  OnLogInitMenu
1017  *
1018  * Description :  Handler for WM_INITMENU messages.  Enable, disable,
1019  *                check, and/or uncheck menu options as apropos.
1020  *
1021  * Parameters  :
1022  *          1  :  hmenu = handle to menu to "make current"
1023  *
1024  * Returns     :  N/A
1025  *
1026  *********************************************************************/
1027 void OnLogInitMenu(HMENU hmenu)
1028 {
1029    /* Only enable editors if there is a file to edit */
1030    EnableMenuItem(hmenu, ID_TOOLS_EDITDEFAULTACTIONS, MF_BYCOMMAND | (g_default_actions_file ? MF_ENABLED : MF_GRAYED));
1031    EnableMenuItem(hmenu, ID_TOOLS_EDITUSERACTIONS, MF_BYCOMMAND | (g_user_actions_file ? MF_ENABLED : MF_GRAYED));
1032    EnableMenuItem(hmenu, ID_TOOLS_EDITDEFAULTFILTERS, MF_BYCOMMAND | (g_default_filterfile ? MF_ENABLED : MF_GRAYED));
1033    EnableMenuItem(hmenu, ID_TOOLS_EDITUSERFILTERS, MF_BYCOMMAND | (g_user_filterfile ? MF_ENABLED : MF_GRAYED));
1034 #ifdef FEATURE_TRUST
1035    EnableMenuItem(hmenu, ID_TOOLS_EDITTRUST, MF_BYCOMMAND | (g_trustfile ? MF_ENABLED : MF_GRAYED));
1036 #endif /* def FEATURE_TRUST */
1037
1038    /* Check/uncheck options */
1039    CheckMenuItem(hmenu, ID_VIEW_LOGMESSAGES, MF_BYCOMMAND | (g_bLogMessages ? MF_CHECKED : MF_UNCHECKED));
1040    CheckMenuItem(hmenu, ID_VIEW_MESSAGEHIGHLIGHTING, MF_BYCOMMAND | (g_bHighlightMessages ? MF_CHECKED : MF_UNCHECKED));
1041    CheckMenuItem(hmenu, ID_VIEW_LIMITBUFFERSIZE, MF_BYCOMMAND | (g_bLimitBufferSize ? MF_CHECKED : MF_UNCHECKED));
1042    CheckMenuItem(hmenu, ID_VIEW_ACTIVITYANIMATION, MF_BYCOMMAND | (g_bShowActivityAnimation ? MF_CHECKED : MF_UNCHECKED));
1043 #ifdef FEATURE_TOGGLE
1044    /* by haroon - menu item for Enable toggle on/off */
1045    CheckMenuItem(hmenu, ID_TOGGLE_ENABLED, MF_BYCOMMAND | (global_toggle_state ? MF_CHECKED : MF_UNCHECKED));
1046 #endif /* def FEATURE_TOGGLE */
1047    CheckMenuItem(hmenu, ID_TOGGLE_SHOWWINDOW, MF_BYCOMMAND | (g_bShowLogWindow ? MF_CHECKED : MF_UNCHECKED));
1048
1049 }
1050
1051
1052 /*********************************************************************
1053  *
1054  * Function    :  OnLogTimer
1055  *
1056  * Description :  Handler for WM_TIMER messages.
1057  *
1058  * Parameters  :
1059  *          1  :  nTimer = timer id (animation start/stop or clip buffer)
1060  *
1061  * Returns     :  N/A
1062  *
1063  *********************************************************************/
1064 void OnLogTimer(int nTimer)
1065 {
1066    switch (nTimer)
1067    {
1068       case TIMER_ANIM_ID:
1069          TraySetIcon(g_hwndTray, 1, g_hiconAnim[g_nAnimFrame++ % ANIM_FRAMES]);
1070          break;
1071
1072       case TIMER_ANIMSTOP_ID:
1073          g_nAnimFrame = 0;
1074          SetIdleIcon();
1075          KillTimer(g_hwndLogFrame, TIMER_ANIM_ID);
1076          KillTimer(g_hwndLogFrame, TIMER_ANIMSTOP_ID);
1077          break;
1078
1079       case TIMER_CLIPBUFFER_ID:
1080       case TIMER_CLIPBUFFER_FORCE_ID:
1081          LogClipBuffer();
1082          g_bClipPending = FALSE;
1083          KillTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_ID);
1084          KillTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_FORCE_ID);
1085          break;
1086
1087       default:
1088          /* DO NOTHING */
1089          break;
1090    }
1091
1092 }
1093
1094
1095 /*********************************************************************
1096  *
1097  * Function    :  SetIdleIcon
1098  *
1099  * Description :  Sets the tray icon to either idle or off
1100  *
1101  * Parameters  :  none
1102  *
1103  * Returns     :  N/A
1104  *
1105  *********************************************************************/
1106 void SetIdleIcon()
1107 {
1108 #ifdef FEATURE_TOGGLE
1109          if (!global_toggle_state)
1110          {
1111             TraySetIcon(g_hwndTray, 1, g_hiconOff);
1112          }
1113          else
1114 #endif /* def FEATURE_TOGGLE */
1115          TraySetIcon(g_hwndTray, 1, g_hiconIdle);
1116 }
1117
1118
1119 /*********************************************************************
1120  *
1121  * Function    :  LogRichEditProc
1122  *
1123  * Description :  Window subclass routine handles some events for the rich edit control.
1124  *
1125  * Parameters  :
1126  *          1  :  hwnd = window handle of the rich edit control
1127  *          2  :  uMsg = message number
1128  *          3  :  wParam = first param for this message
1129  *          4  :  lParam = next param for this message
1130  *
1131  * Returns     :  Appropriate M$ window message handler codes.
1132  *
1133  *********************************************************************/
1134 LRESULT CALLBACK LogRichEditProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1135 {
1136    switch (uMsg)
1137    {
1138       case WM_RBUTTONUP:
1139       {
1140          POINT pt;
1141          pt.x = LOWORD(lParam);
1142          pt.y = HIWORD(lParam);
1143          ClientToScreen(hwnd, &pt);
1144          OnLogRButtonUp(wParam, pt.x, pt.y);
1145          return 0;
1146       }
1147       case WM_CHAR:
1148       {
1149          if ((GetKeyState(VK_CONTROL) != 0) && (wParam == 4)) /* ctrl+d */
1150          {
1151              OnLogCommand(ID_VIEW_CLEARLOG);
1152              return 0;
1153          }
1154       }
1155    }
1156    return CallWindowProc(g_fnLogBox, hwnd, uMsg, wParam, lParam);
1157
1158 }
1159
1160
1161 /*********************************************************************
1162  *
1163  * Function    :  LogWindowProc
1164  *
1165  * Description :  Windows call back routine handles events on the log window.
1166  *
1167  * Parameters  :
1168  *          1  :  hwnd = handle of the logging window
1169  *          2  :  uMsg = message number
1170  *          3  :  wParam = first param for this message
1171  *          4  :  lParam = next param for this message
1172  *
1173  * Returns     :  Appropriate M$ window message handler codes.
1174  *
1175  *********************************************************************/
1176 LRESULT CALLBACK LogWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1177 {
1178    switch (uMsg)
1179    {
1180       case WM_CREATE:
1181          return 0;
1182
1183       case WM_CLOSE:
1184          /* This is the end - my only friend - the end */
1185          DestroyWindow(g_hwndLogBox);
1186          DestroyWindow(g_hwndLogFrame);
1187          return 0;
1188
1189       case WM_DESTROY:
1190          PostQuitMessage(0);
1191          return 0;
1192
1193       case WM_SHOWWINDOW:
1194          g_bShowLogWindow = wParam;
1195       case WM_SIZE:
1196          /* Resize the logging window to fit the new frame */
1197          if (g_hwndLogBox)
1198          {
1199             RECT rc;
1200             GetClientRect(g_hwndLogFrame, &rc);
1201             SetWindowPos(g_hwndLogBox, NULL, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, SWP_NOZORDER);
1202          }
1203          return 0;
1204
1205       case WM_INITMENU:
1206          OnLogInitMenu((HMENU) wParam);
1207          return 0;
1208
1209       case WM_TIMER:
1210          OnLogTimer(wParam);
1211          return 0;
1212
1213       case WM_COMMAND:
1214          OnLogCommand(LOWORD(wParam));
1215          return 0;
1216
1217       case WM_SYSCOMMAND:
1218          switch (wParam)
1219          {
1220             case SC_CLOSE:
1221                if (g_bCloseHidesWindow)
1222                {
1223                   ShowLogWindow(FALSE);
1224                   return 0;
1225                }
1226                break;
1227             case SC_MINIMIZE:
1228                ShowLogWindow(FALSE);
1229                return 0;
1230          }
1231          break;
1232
1233       case WM_CHAR:
1234          if ((GetKeyState(VK_CONTROL) != 0) && (wParam == 4)) /* ctrl+d */
1235          {
1236              OnLogCommand(ID_VIEW_CLEARLOG);
1237              return 0;
1238          }
1239          break;
1240    }
1241
1242    return DefWindowProc(hwnd, uMsg, wParam, lParam);
1243
1244 }
1245
1246 #endif /* ndef _WIN_CONSOLE - entire file */
1247
1248 /*
1249   Local Variables:
1250   tab-width: 3
1251   end:
1252 */