File: smtpappender.cpp

package info (click to toggle)
log4cxx 0.10.0-15
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 17,116 kB
  • sloc: cpp: 33,940; sh: 8,717; xml: 4,686; makefile: 507; java: 48
file content (674 lines) | stat: -rw-r--r-- 20,607 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
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <log4cxx/net/smtpappender.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/helpers/optionconverter.h>
#include <log4cxx/spi/loggingevent.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/stringtokenizer.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/helpers/synchronized.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/private/log4cxx_private.h>



#include <apr_strings.h>
#include <vector>

using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::net;
using namespace log4cxx::spi;

#if LOG4CXX_HAVE_LIBESMTP
#include <auth-client.h>
#include <libesmtp.h>
#endif

namespace log4cxx {
    namespace net {
        //
        //   The following two classes implement an C++ SMTP wrapper over libesmtp.
        //   The same signatures could be implemented over different SMTP implementations
        //   or libesmtp could be combined with libgmime to enable support for non-ASCII
        //   content.  

#if LOG4CXX_HAVE_LIBESMTP        
        /**
         *   SMTP Session.
         */
        class SMTPSession {
        public:
           /**
           *   Create new instance.
           */
            SMTPSession(const LogString& smtpHost,
                        int smtpPort,
                        const LogString& smtpUsername,
                        const LogString& smtpPassword,
                        Pool& p) : session(0), authctx(0), 
                        user(toAscii(smtpUsername, p)), 
                        pwd(toAscii(smtpPassword, p)) {
                auth_client_init();
                session = smtp_create_session();
                if (session == 0) {
                    throw Exception("Could not initialize session.");
                }
                std::string host(toAscii(smtpHost, p));
                host.append(1, ':');
                host.append(p.itoa(smtpPort));
                smtp_set_server(session, host.c_str());
   
                authctx = auth_create_context();
                auth_set_mechanism_flags(authctx, AUTH_PLUGIN_PLAIN, 0);
                auth_set_interact_cb(authctx, authinteract, (void*) this);
   
                if (*user || *pwd) {
                    smtp_auth_set_context(session, authctx);
                }
            }
            
            ~SMTPSession() {
                 smtp_destroy_session(session);
                 auth_destroy_context(authctx);
            }
            
            void send(Pool& p) {
                 int status = smtp_start_session(session);
                 if (!status) {
                     size_t bufSize = 128;
                     char* buf = p.pstralloc(bufSize);
                     smtp_strerror(smtp_errno(), buf, bufSize);
                     throw Exception(buf);
                 }
            }
            
            operator smtp_session_t() {
                return session;
            }

            static char* toAscii(const LogString& str, Pool& p) {
                char* buf = p.pstralloc(str.length() + 1);
                char* current = buf;
                for(LogString::const_iterator iter = str.begin();
                    iter != str.end();
                    iter++) {
                    unsigned int c = *iter;
                    if (c > 0x7F) {
                       c = '?';
                    }
                    *current++ = c;
                }
                *current = 0;
                return buf;
            }
                        
            private:
            SMTPSession(SMTPSession&);
            SMTPSession& operator=(SMTPSession&);
            smtp_session_t session;
            auth_context_t authctx;
            char* user;
            char* pwd;

            /**
             *   This method is called if the SMTP server requests authentication.
             */
            static int authinteract(auth_client_request_t request, char **result, int fields,
              void *arg) {
              SMTPSession* pThis = (SMTPSession*) arg;
              for (int i = 0; i < fields; i++) {
                int flag = request[i].flags & 0x07;
                if (flag == AUTH_USER) {
                   result[i] = pThis->user;
                } else if(flag == AUTH_PASS) {
                   result[i] = pThis->pwd;
                }
              }
              return 1;
            }
            

        };
        
        /**
         *  A message in an SMTP session.
         */
        class SMTPMessage {
        public:
            SMTPMessage(SMTPSession& session, 
                        const LogString& from, 
                        const LogString& to,
                        const LogString& cc,
                        const LogString& bcc,
                        const LogString& subject,
                        const LogString msg, Pool& p) {
                 message = smtp_add_message(session);
                 body = current = toMessage(msg, p);
                 smtp_set_reverse_path(message, toAscii(from, p));
                 addRecipients(to, "To", p);
                 addRecipients(cc, "Cc", p);
                 addRecipients(bcc, "Bcc", p);
                 if (!subject.empty()) {
                    smtp_set_header(message, "Subject", toAscii(subject, p));
                 }
                 smtp_set_messagecb(message, messagecb, this); 
            }
            ~SMTPMessage() {
            }
            
        private:
           SMTPMessage(const SMTPMessage&);
           SMTPMessage& operator=(const SMTPMessage&);
           smtp_message_t message;
           const char* body;
           const char* current;
           void addRecipients(const LogString& addresses, const char* field, Pool& p) {
              if (!addresses.empty()) {
                char* str = p.pstrdup(toAscii(addresses, p));;
                smtp_set_header(message, field, NULL, str);
                char* last;
                for(char* next = apr_strtok(str, ",", &last);
                    next;
                    next = apr_strtok(NULL, ",", &last)) {
                    smtp_add_recipient(message, next);
                }
              }
          }
           static const char* toAscii(const LogString& str, Pool& p) {
               return SMTPSession::toAscii(str, p);
           }
           
           /**
            *   Message bodies can only contain US-ASCII characters and 
            *   CR and LFs can only occur together.
            */
           static const char* toMessage(const LogString& str, Pool& p) {
               //
               //    count the number of carriage returns and line feeds
               //
               int feedCount = 0;
               for(size_t pos = str.find_first_of(LOG4CXX_STR("\n\r"));
                   pos != LogString::npos;
                   pos = str.find_first_of(LOG4CXX_STR("\n\r"), ++pos)) {
                   feedCount++;
               }
               //
               //   allocate sufficient space for the modified message
               char* retval = p.pstralloc(str.length() + feedCount + 1);
               char* current = retval;
               char* startOfLine = current;
               //
               //    iterator through message
               //
               for(LogString::const_iterator iter = str.begin();
                   iter != str.end();
                   iter++) {
                   unsigned int c = *iter;
                   //
                   //   replace non-ASCII characters with '?'
                   //
                   if (c > 0x7F) {
                      *current++ = 0x3F; // '?'
                   } else if (c == 0x0A || c == 0x0D) {
                      //
                      //   replace any stray CR or LF with CRLF
                      //      reset start of line
                      *current++ = 0x0D;
                      *current++ = 0x0A;
                      startOfLine = current;
                      LogString::const_iterator next = iter + 1;
                      if (next != str.end() && (*next == 0x0A || *next == 0x0D)) {
                         iter++;
                      }
                   } else {
                      //
                      //    truncate any lines to 1000 characters (including CRLF)
                      //       as required by RFC.
                      if (current < startOfLine + 998) {
                        *current++ = (char) c;
                      }
                   }
               }
               *current = 0;
               return retval;
           }
           
           /**
            *  Callback for message.
            */
           static const char* messagecb(void** ctx, int* len, void* arg) {
               *ctx = 0;
               const char* retval = 0;
               SMTPMessage* pThis = (SMTPMessage*) arg;
               //   rewind message
               if (len == NULL) {
                   pThis->current = pThis->body;
               } else {
                  if (pThis->current) {
                    *len = strlen(pThis->current);
                  }
                  retval = pThis->current;
                  pThis->current = 0;
               }
               return retval;
           }
           
        };
#endif        
        
                class LOG4CXX_EXPORT DefaultEvaluator :
                        public virtual spi::TriggeringEventEvaluator,
                        public virtual helpers::ObjectImpl
                {
                public:
                        DECLARE_LOG4CXX_OBJECT(DefaultEvaluator)
                        BEGIN_LOG4CXX_CAST_MAP()
                                LOG4CXX_CAST_ENTRY(DefaultEvaluator)
                                LOG4CXX_CAST_ENTRY(spi::TriggeringEventEvaluator)
                        END_LOG4CXX_CAST_MAP()

                        DefaultEvaluator();

                        /**
                        Is this <code>event</code> the e-mail triggering event?
                        <p>This method returns <code>true</code>, if the event level
                        has ERROR level or higher. Otherwise it returns
                        <code>false</code>.
                        */
                        virtual bool isTriggeringEvent(const spi::LoggingEventPtr& event);
                private:
                         DefaultEvaluator(const DefaultEvaluator&);
                         DefaultEvaluator& operator=(const DefaultEvaluator&);
                }; // class DefaultEvaluator
        
    }
}

IMPLEMENT_LOG4CXX_OBJECT(DefaultEvaluator)
IMPLEMENT_LOG4CXX_OBJECT(SMTPAppender)

DefaultEvaluator::DefaultEvaluator() {
}

bool DefaultEvaluator::isTriggeringEvent(const spi::LoggingEventPtr& event)
{
   return event->getLevel()->isGreaterOrEqual(Level::getError());
}

SMTPAppender::SMTPAppender()
: smtpPort(25), bufferSize(512), locationInfo(false), cb(bufferSize),
evaluator(new DefaultEvaluator())
{
}

/**
Use <code>evaluator</code> passed as parameter as the
TriggeringEventEvaluator for this SMTPAppender.  */
SMTPAppender::SMTPAppender(spi::TriggeringEventEvaluatorPtr evaluator)
: smtpPort(25), bufferSize(512), locationInfo(false), cb(bufferSize),
evaluator(evaluator)
{
}

SMTPAppender::~SMTPAppender()
{
   finalize();
}

bool SMTPAppender::requiresLayout() const { 
    return true; 
}


LogString SMTPAppender::getFrom() const {
    return from;
}

void SMTPAppender::setFrom(const LogString& newVal) {
    from = newVal;
}


LogString SMTPAppender::getSubject() const {
    return subject;
}

void SMTPAppender::setSubject(const LogString& newVal) {
    subject = newVal;
}

LogString SMTPAppender::getSMTPHost() const {
    return smtpHost;
}

void SMTPAppender::setSMTPHost(const LogString& newVal) {
    smtpHost = newVal;
}

int SMTPAppender::getSMTPPort() const {
    return smtpPort;
}

void SMTPAppender::setSMTPPort(int newVal) {
    smtpPort = newVal;
}

bool SMTPAppender::getLocationInfo() const {
   return locationInfo;
}

void SMTPAppender::setLocationInfo(bool newVal) { 
    locationInfo = newVal; 
}

LogString SMTPAppender::getSMTPUsername() const {
    return smtpUsername;
}

void SMTPAppender::setSMTPUsername(const LogString& newVal) {
    smtpUsername = newVal;
}

LogString SMTPAppender::getSMTPPassword() const {
    return smtpPassword;
}

void SMTPAppender::setSMTPPassword(const LogString& newVal) {
    smtpPassword = newVal;
}





void SMTPAppender::setOption(const LogString& option,
   const LogString& value)
{
   if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize")))
   {
      setBufferSize(OptionConverter::toInt(value, 512));
   }
   else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("EVALUATORCLASS"), LOG4CXX_STR("evaluatorclass")))
   {
      setEvaluatorClass(value);
   }
   else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FROM"), LOG4CXX_STR("from")))
   {
      setFrom(value);
   }
   else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPHOST"), LOG4CXX_STR("smtphost")))
   {
      setSMTPHost(value);
   }
   else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPUSERNAME"), LOG4CXX_STR("smtpusername")))
   {
      setSMTPUsername(value);
   }
   else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPPASSWORD"), LOG4CXX_STR("smtppassword")))
   {
      setSMTPPassword(value);
   }
   else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SUBJECT"), LOG4CXX_STR("subject")))
   {
      setSubject(value);
   }
   else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("TO"), LOG4CXX_STR("to")))
   {
      setTo(value);
   }
   else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("CC"), LOG4CXX_STR("cc")))
   {
      setCc(value);
   }
   else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BCC"), LOG4CXX_STR("bcc")))
   {
      setBcc(value);
   }
   else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPPORT"), LOG4CXX_STR("smtpport")))
   {
      setSMTPPort(OptionConverter::toInt(value, 25));
   }
   else
   {
      AppenderSkeleton::setOption(option, value);
   }
}


bool SMTPAppender::asciiCheck(const LogString& value, const LogString& field) {
     for(LogString::const_iterator iter = value.begin();
         iter != value.end();
         iter++) {
         if (0x7F < (unsigned int) *iter) {
            LogLog::warn(field + LOG4CXX_STR(" contains non-ASCII character"));
            return false;
         } 
     }
     return true;
}

/**
Activate the specified options, such as the smtp host, the
recipient, from, etc. */
void SMTPAppender::activateOptions(Pool& p)
{
   bool activate = true;
   if (layout == 0) {
      LogLog::error(LOG4CXX_STR("No layout set for appender named [") +name+ LOG4CXX_STR("]."));
      activate = false;
   }
   if(evaluator == 0) {
      LogLog::error(LOG4CXX_STR("No TriggeringEventEvaluator is set for appender [")+
          name+LOG4CXX_STR("]."));
      activate = false;
   }
   if(smtpHost.empty()) {
      LogLog::error(LOG4CXX_STR("No smtpHost is set for appender [")+
          name+LOG4CXX_STR("]."));
      activate = false;
   }
   if(to.empty() && cc.empty() && bcc.empty()) {
      LogLog::error(LOG4CXX_STR("No recipient address is set for appender [")+
          name+LOG4CXX_STR("]."));
      activate = false;
   }
   activate &= asciiCheck(to, LOG4CXX_STR("to"));
   activate &= asciiCheck(cc, LOG4CXX_STR("cc"));
   activate &= asciiCheck(bcc, LOG4CXX_STR("bcc"));
   activate &= asciiCheck(from, LOG4CXX_STR("from"));
 
#if !LOG4CXX_HAVE_LIBESMTP
   LogLog::error(LOG4CXX_STR("log4cxx built without SMTP support."));
   activate = false;
#endif     
   if (activate) {
        AppenderSkeleton::activateOptions(p);
   }
}

/**
Perform SMTPAppender specific appending actions, mainly adding
the event to a cyclic buffer and checking if the event triggers
an e-mail to be sent. */
void SMTPAppender::append(const spi::LoggingEventPtr& event, Pool& p)
{
   if(!checkEntryConditions())
   {
      return;
   }

   LogString ndc;
   event->getNDC(ndc);
   event->getThreadName();
   // Get a copy of this thread's MDC.
   event->getMDCCopy();

   cb.add(event);

   if(evaluator->isTriggeringEvent(event))
   {
      sendBuffer(p);
   }
}

/**
This method determines if there is a sense in attempting to append.
<p>It checks whether there is a set output target and also if
there is a set layout. If these checks fail, then the boolean
value <code>false</code> is returned. */
bool SMTPAppender::checkEntryConditions()
{
#if LOG4CXX_HAVE_LIBESMTP
   if((to.empty() && cc.empty() && bcc.empty()) || from.empty() || smtpHost.empty())
   {
      errorHandler->error(LOG4CXX_STR("Message not configured."));
      return false;
   }

   if(evaluator == 0)
   {
      errorHandler->error(LOG4CXX_STR("No TriggeringEventEvaluator is set for appender [")+
         name+ LOG4CXX_STR("]."));
      return false;
   }


   if(layout == 0)
   {
      errorHandler->error(LOG4CXX_STR("No layout set for appender named [")+name+LOG4CXX_STR("]."));
      return false;
   }
   return true;
#else
   return false;
#endif   
}



void SMTPAppender::close() {
   this->closed = true;
}

LogString SMTPAppender::getTo() const{
   return to;
}

void SMTPAppender::setTo(const LogString& addressStr) {
     to = addressStr;
}

LogString SMTPAppender::getCc() const{
   return cc;
}

void SMTPAppender::setCc(const LogString& addressStr) {
     cc = addressStr;
}

LogString SMTPAppender::getBcc() const{
   return bcc;
}

void SMTPAppender::setBcc(const LogString& addressStr) {
     bcc = addressStr;
}

/**
Send the contents of the cyclic buffer as an e-mail message.
*/
void SMTPAppender::sendBuffer(Pool& p)
{
#if LOG4CXX_HAVE_LIBESMTP
   // Note: this code already owns the monitor for this
   // appender. This frees us from needing to synchronize on 'cb'.
   try
   {
      LogString sbuf;
      layout->appendHeader(sbuf, p);

      int len = cb.length();
      for(int i = 0; i < len; i++)
      {
         LoggingEventPtr event = cb.get();
         layout->format(sbuf, event, p);
      }

      layout->appendFooter(sbuf, p);

      SMTPSession session(smtpHost, smtpPort, smtpUsername, smtpPassword, p);
      
      SMTPMessage message(session, from, to, cc, 
          bcc, subject, sbuf, p);
      
      session.send(p);

   }
   catch(std::exception& e)
   {
      LogLog::error(LOG4CXX_STR("Error occured while sending e-mail notification."), e);
   }
#endif   
}

/**
Returns value of the <b>EvaluatorClass</b> option.
*/
LogString SMTPAppender::getEvaluatorClass()
{
   return evaluator == 0 ? LogString() : evaluator->getClass().getName();
}

log4cxx::spi::TriggeringEventEvaluatorPtr SMTPAppender::getEvaluator() const {
   return evaluator;
}

void SMTPAppender::setEvaluator(log4cxx::spi::TriggeringEventEvaluatorPtr& trigger) {
    evaluator = trigger;
}

/**
The <b>BufferSize</b> option takes a positive integer
representing the maximum number of logging events to collect in a
cyclic buffer. When the <code>BufferSize</code> is reached,
oldest events are deleted as new events are added to the
buffer. By default the size of the cyclic buffer is 512 events.
*/
void SMTPAppender::setBufferSize(int bufferSize)
{
   this->bufferSize = bufferSize;
   cb.resize(bufferSize);
}

/**
The <b>EvaluatorClass</b> option takes a string value
representing the name of the class implementing the {@link
TriggeringEventEvaluator} interface. A corresponding object will
be instantiated and assigned as the triggering event evaluator
for the SMTPAppender.
*/
void SMTPAppender::setEvaluatorClass(const LogString& value)
{
   evaluator = OptionConverter::instantiateByClassName(value,
      TriggeringEventEvaluator::getStaticClass(), evaluator);
}