void TMailProcessor::Send(const TIdentity& senderId, const TPhysicalMailMessage& msg) { TPhysicalMailMessage msgToSend(msg); TRecipientPublicKeys bccList(msg.bcc_list); /// \warning Message to be sent must have cleared bcc list. msgToSend.bcc_list.clear(); size_t totalRecipientCount = msgToSend.to_list.size() + msgToSend.cc_list.size() + bccList.size(); //Sink.OnMessageGroupPending(totalRecipientCount); //Sink.OnMessagePending auto my_priv_key = Profile->get_keychain().get_identity_key(senderId.dac_id_string); auto app = bts::application::instance(); for(const auto& public_key : msgToSend.to_list) app->send_email(msgToSend, public_key, my_priv_key); for(const auto& public_key : msgToSend.cc_list) app->send_email(msgToSend, public_key, my_priv_key); for(const auto& public_key : bccList) app->send_email(msgToSend, public_key, my_priv_key); }
bool smtp_client::send(const mail_message& message, const char* email /* = NULL */) { // 发送 SMTP 邮件信封过程 if (send_envelope(message) == false) return false; // 优先使用参数给出的邮件文件,然后才是 message 中自动生成的邮件文件 if (email == NULL) email = message.get_email(); // 如果没有可发送的邮件文件,则认为调用者想通过 write 等接口直接发送数据 if (email == NULL) return true; // 发送 DATA 命令 if (data_begin() == false) return false; // 发送邮件 if (send_email(email) == false) return false; // 发送 DATA 结束符 return data_end(); }
int main(int argc, char **argv) { int result; struct email *email; email = alloc_email(); result = parse_arguments(argc, argv, email); if (result != 0) { free_email(email); return 1; } result = send_email(email); if (result != 0) { free_email(email); return 1; } free_email(email); return 0; }
boolean send_passwd_to_user_email_address(char *email_to, char *username, boolean is_admin_flag, char *passwd) { printf("***passwd: %s\n", passwd); char payload_msg[EMAIL_MSG_LINE_LENGTH + 1]; sprintf(payload_msg, "To: %s\n", email_to); send_email_config_payload(0, payload_msg); sprintf(payload_msg, "From: %s(%s's mailer)\n", GLOBAL_authority_email_address, GLOBAL_authority_name); send_email_config_payload(1, payload_msg); sprintf(payload_msg, "Subject: Your account's password\n"); send_email_config_payload(2, payload_msg); sprintf(payload_msg, "\n"); // Empty line to divide headers from body, see RFC5322 send_email_config_payload(3, payload_msg); sprintf(payload_msg, "Authority name = \"%s(EmU)\"\n", GLOBAL_authority_name); send_email_config_payload(4, payload_msg); sprintf(payload_msg, "Username = \"%s\"\n", username); send_email_config_payload(5, payload_msg); sprintf(payload_msg, "Status = \"%s\"\n", (is_admin_flag) ? "EmU's administrator" : "EmU's user"); send_email_config_payload(6, payload_msg); sprintf(payload_msg, "Password = \"%s\"\n", passwd); send_email_config_payload(7, payload_msg); payload_msg[0] = 0; // Fill a NULL terminated character to tell a send_main() that end of payload send_email_config_payload(8, payload_msg); return send_email(email_to); }
void Log::add(ssh_wcs msg) { if(_log) { String _msg(apply_template(L"", L"", 0, 0, msg, _log->trace_template)); switch(_log->_out) { case TypeOutput::Net: if(sock.is_closed()) { sock.init(_log->host_name, 0, _log->host_flags, _log->host_cert, _log->host_pwd_cert); sendSocket(_log->string_begin); } sendSocket(_msg); break; case TypeOutput::File: if(!file.is_close()) file.write(_msg, L"utf-8"); break; case TypeOutput::Mail: if(!_log->email_blocked) { if(!file.is_close()) file.write(_msg, cp_utf); _log->email_count_msgs++; if(_log->email_count_msgs >= _log->email_max_msgs) send_email(_log->string_continue); } break; case TypeOutput::Debug: OutputDebugStringW(_msg); break; } } }
void send_icqpage(UR_OBJECT user, char *inpstr) { char fname[FNAME_LEN], icqnum[ICQ_LEN+1], subj[100], addr[100]; int on; UR_OBJECT ur; FILE *fp; if (word_count<3) { write_usage(user, "%s <user>/<ICQ#> <text>", command_table[ICQPAGE].name); return; } icqnum[0]='\0'; if (is_number(word[1])) strncpy(icqnum, word[1], ICQ_LEN); else { if (!(ur=get_user_name(user, word[1]))) { if (!(ur=create_user())) { vwrite_user(user, "%s: nemozem vytvorit docasny user objekt.\n", syserror); write_syslog(ERRLOG, 1, "Unable to create temp user object in send_icqpage()\n"); return; } strcpy(ur->name, word[1]); if (!load_user_details(ur)) { write_user(user, nosuchuser); destruct_user(ur); destructed=0; return; } on=0; } else on=1; strcpy(icqnum, ur->icq); if (!on) { destruct_user(ur); destructed=0; } } if (icqnum[0]=='\0') { write_user(user, "sprava neposlana, chybne alebo nezistitelne ICQ cislo\n"); return; } sprintf(fname, "%s/%s.icq", TEMPFILES, user->name); if (!(fp=fopen(fname, "w"))) { write_user(user, "nemozem vytvorit docasny subor pre spravu\n"); write_syslog(ERRLOG, 1, "unable to open file in send_icqpage()\n"); return; } fprintf(fp, icq_page_email); fprintf(fp, "%s\n", remove_first(inpstr)); fclose(fp); sprintf(addr, "*****@*****.**", icqnum); sprintf(subj, "ICQ page from %s", user->name); send_email(addr, subj, fname); write_user(user, "sprava bola odoslana\n"); }
/* Send artifacts with email. */ void send_artifacts_with_email (GSList *attachment_list) { gchar *to = "*****@*****.**"; gchar *subject = "ardesia-contribution"; gchar *body = g_strdup_printf ("%s,\n%s,%s.", "Dear ardesia developer group", "I want share my work created with Ardesia with you", "please for details see the attachment" ); send_email (to, subject, body, attachment_list); g_free (body); }
void Log::add(TypeMessage type, ssh_wcs fn, ssh_wcs fl, int ln, ssh_wcs msg, ...) { if(_log) { if(!tracer.is_disabled) { tracer.stop(); String msgArgs; // формируем сообщение va_list arglist; va_start(arglist, msg); msgArgs.fmt(msg, arglist); va_end(arglist); msgArgs.replace(L'\r', L'.'); msgArgs.replace(L'\n', L'.'); // формируем сообщение на основании шаблона switch(_log->_out) { case TypeOutput::Net: if(sock.is_closed()) { sock.init(_log->host_name, 0, _log->host_flags, _log->host_cert, _log->host_pwd_cert); sendSocket(_log->string_begin); } sendSocket(apply_template(fn, fl, ln, type, msgArgs, _log->file_template)); break; case TypeOutput::Screen: if(MessageBox(nullptr, apply_template(fn, fl, ln, type, msgArgs, _log->screen_template), ssh_system_paths(SystemInfo::siNameProg), MB_ICONERROR | MB_YESNO) == IDNO) { exit(4); } break; case TypeOutput::File: if(!file.is_close()) file.write(apply_template(fn, fl, ln, type, msgArgs, _log->file_template), L"utf-8"); break; case TypeOutput::Mail: if(!_log->email_blocked) { if(!file.is_close()) file.write(apply_template(fn, fl, ln, type, msgArgs, _log->email_template), cp_utf); _log->email_count_msgs++; if(_log->email_count_msgs >= _log->email_max_msgs) send_email(_log->string_continue); } break; case TypeOutput::Debug: OutputDebugStringW(apply_template(fn, fl, ln, type, msgArgs, _log->debug_template)); break; } tracer.start(); } } }
/* Send trace with email. */ void send_trace_with_email (gchar *attachment) { GSList *attachment_list = NULL; gchar *to = "*****@*****.**"; gchar *subject = "ardesia-bug-report"; gchar *body = g_strdup_printf ("%s,\n%s,%s.", "Dear ardesia developer group", "An application error occurred", "please for details see the attachment with the stack trace" ); attachment_list = g_slist_prepend (attachment_list, attachment); send_email (to, subject, body, attachment_list); g_free (body); }
/* send notifcations out to all people(s) state is the 1 (up) or 0 (down), -1 error */ void send_notifications(char *hostname, int port, int state) { char buffer[255]; MYSQL *mysqlConnection; MYSQL_RES *res; MYSQL_ROW row; char qry[1024], buf[128]; int ql; mysqlConnection = init_sql(); if (!mysqlConnection) return; sprintf(buf, "%s %d %s", hostname, port, ((state == 1) ? "up" : "down") ); strcpy(qry, "SELECT pager,send_page,email,send_email,id FROM notifications"); ql = strlen(qry); if (mysql_real_query(mysqlConnection, qry, ql)) return; if (! (res = mysql_store_result(mysqlConnection)) ) return; while ((row = mysql_fetch_row(res))) { if (wants_notification(hostname, atoi(row[4]))) { #ifdef ARCH_HTTP_PAGE if (strcmp(row[1], "1") == 0) { /* send page */ /* check if they want to receive pages for this server */ sprintf(buffer, " sending page to %s...\n", row[0]); _log(buffer, 1); send_page(row[0], buf); } #endif if (strcmp(row[3], "1") == 0) { /* send e-mail */ sprintf(buffer, " sending email to %s...\n", row[2]); _log(buffer, 1); send_email(row[2], buf); } } } mysql_free_result(res); close_sql(mysqlConnection); }
/*** verify user's email when it is set specified ***/ void set_forward_email(UR_OBJECT user) { FILE *fp; char fname[FNAME_LEN]; set_crash(); if (!user->email[0] || !strcmp(user->email,"#UNSET")) { write_user(user,"Your email address is currently ~FRunset~RS. If you wish to use the\nauto-forwarding function then you must set your email address.\n\n"); user->autofwd=0; return; } if (!amsys->forwarding) { write_user(user,"Even though you have set your email, the auto-forwarding function is currently unavaliable.\n"); user->mail_verified=0; user->autofwd=0; return; } user->mail_verified=0; user->autofwd=0; /* Let them know by email */ sprintf(fname,"%s/%s.FWD",MAILSPOOL,user->name); if (!(fp=fopen(fname,"w"))) { write_syslog(ERRLOG, 1, "Unable to open forward mail file in set_forward_email()\n"); return; } sprintf(user->verify_code,"lotos%d",rand()%999); /* email header */ fprintf(fp,"From: %s\n",reg_sysinfo[TALKERNAME]); fprintf(fp,"To: %s <%s>\n\n",user->name,user->email); /* email body */ fprintf(fp,"Hello, %s.\n\n",user->name); fprintf(fp, vrf_fwd_email, user->verify_code); fputs(talker_signature,fp); fclose(fp); /* send the mail */ send_email(user->email, "Verification of auto-mail", fname); write_syslog(SYSLOG,1,"%s had mail sent to them by set_forward_email().\n",user->name); /* Inform them online */ write_user(user,"Now that you have set your email you can use the auto-forward functions.\n"); write_user(user,"You must verify your address with the code you will receive shortly, via email.\n"); write_user(user,"If you do not receive any email, then use ~FTset email <email>~RS again, making\nsure you have the correct address.\n\n"); }
static void end_slot(int slot, int status) { struct stat st; slots[slot].pid = 0; --slots_used; if (slots[slot].sending_email) { slots[slot].sending_email = 0; if (status) report_slot(slot, "ZJob complete, sending email failed"); else report_slot(slot, "KJob complete, email sent"); } else { /* No header, no possible way to send email. */ if (slots[slot].headerlen == 0) report_slot(slot, "KJob complete, no MAILTO"); else { /* If the job crashed, make sure it is noted. */ if (WIFSIGNALED(status)) { debugf(DEBUG_EXEC, "{slot }d{ Job was killed by signal #}d", slot, WTERMSIG(status)); wrap_str(str_copys(&tmp, "\n\nJob was killed by signal #")); wrap_str(str_cati(&tmp, WTERMSIG(status))); wrap_str(str_catc(&tmp, '\n')); write(slots[slot].tmpfd, tmp.s, tmp.len); } if (fstat(slots[slot].tmpfd, &st) == -1) failsys_slot(slot, "ZCould not fstat"); else if (st.st_size > slots[slot].headerlen) send_email(slot); else report_slot(slot, "KJob complete, no mail sent"); } /* To simplify the procedure, close the temporary file early. * The email sender still has it open, and will effect the final * deletion of the file when it completes. */ if (slots[slot].tmpfd != devnull) close(slots[slot].tmpfd); slots[slot].tmpfd = -1; } }
static pmix_status_t mylog(const pmix_proc_t *source, const pmix_info_t data[], size_t ndata, const pmix_info_t directives[], size_t ndirs, pmix_op_cbfunc_t cbfunc, void *cbdata) { char *output, *msg; size_t n; bool generic = false, local = false, global = fals; time_t timestamp; /* if there are no directives, then we don't handle it */ if (NULL == directives || 0 == ndirs) { return PMIX_ERR_NOT_AVAILABLE; } /* check to see if there are any email directives */ for (n=0; n < ndirs; n++) { if (0 == strncmp(directives[n].key, PMIX_LOG_EMAIL, PMIX_MAX_KEYLEN)) { /* we default to using the local syslog */ generic = true; msg = strdup(directives[n].value.data.string); } else if (0 == strncmp(directives[n].key, PMIX_LOG_LOCAL_SYSLOG, PMIX_MAX_KEYLEN)) { local = true; msg = strdup(directives[n].value.data.string); } else if (0 == strncmp(directives[n].key, PMIX_LOG_GLOBAL_SYSLOG, PMIX_MAX_KEYLEN)) { global = true; msg = strdup(directives[n].value.data.string); } else if (0 == strncmp(directives[n].key, PMIX_LOG_SYSLOG_PRI, PMIX_MAX_KEYLEN)) { pri = directives[n].value.data.integer; } else if (0 == strncmp(directives[n].key, PMIX_LOG_TIMESTAMP, PMIX_MAX_KEYLEN)) { timestamp = directives[n].value.data.time; } } /* If there was a message, output it */ vasprintf(&output, msg, ap); if (NULL != output) { send_email(output); free(output); } }
void send_rep_out( CHAR_DATA * ch, char * outbuf, bool mailme, char * msub ) { if ( ( IS_NPC( ch ) ) || ( ch->pcdata->valid_email == FALSE ) ) { mailme = FALSE; } if ( mailme ) { bool saved_mail = FALSE; if ( ( !IS_NPC( ch ) ) && ( str_cmp( ch->pcdata->email_address, "not set" ) ) ) { char mailfilename[MSL]; sprintf( mailfilename, "%s.mail", ch->name ); saved_mail = save_mail_file( mailfilename , outbuf ); if ( saved_mail ) { char outbuf2[MSL]; sprintf( outbuf2, "Email sent to %s\n\r", ch->pcdata->email_address ); send_to_char( outbuf2, ch ); send_email( ch->pcdata->email_address, msub, mailfilename ); } else { send_to_char( outbuf, ch ); send_to_char( "\n\r@@eUNABLE TO SEND SYSTEM MAIL. @@WCheck your sendmail settings.@@N\n\r", ch ); } } else { send_to_char( outbuf, ch ); } } else { send_to_char( outbuf, ch ); } }
void Log::shutdown() { tracer.stop(); MemMgr::instance()->stop(); if(_log) { _log->string_finish = apply_template(L"", L"", 0, 0, L"", _log->string_finish); switch(_log->_out) { case TypeOutput::Net: sendSocket(_log->string_finish); break; case TypeOutput::Screen: break; case TypeOutput::File: if(!file.is_close()) file.write(_log->string_finish, L"utf-8"); break; case TypeOutput::Mail: if(!file.is_close()) file.write(_log->string_finish, cp_utf); send_email(L""); break; case TypeOutput::Debug: OutputDebugStringW(_log->string_finish); break; } _log->_out = TypeOutput::Null; if(hEventSocket) { CloseHandle(hEventSocket); hEventSocket = nullptr; } SSH_DEL(_log); } file.close(); sock.close(); }
int run_watchdog (int pids[], int num_pids, char* port, char* email_address, char* mail_server) { signal (SIGPIPE, SIG_IGN); pid_t pid = fork(); if (pid < 0) { PERR ("fork"); exit (EXIT_FAILURE); } if (pid == 0) { umask(0); openlog ("SPROCKETS_WATCHDOG", LOG_CONS, LOG_DAEMON); pid_t sid = setsid(); if (sid < 0) { PMSG ("Sprockets watchdog failed to setsid. Exiting now.\n"); exit (EXIT_FAILURE); } if ((chdir("/")) < 0) { PMSG ("Sprockets watchdog failed to chdir. Exiting now.\n"); exit (EXIT_FAILURE); } int sigs[] = { SIGINT, SIGQUIT, SIGHUP, SIGCHLD }; int sfd = setup_sighandlers (sigs, 3); if (sfd == 0) { PMSG ("Sprockets watchdog failed to set sighandlers. Exiting now.\n"); exit (EXIT_FAILURE); } int epfd = init_epoll (sfd); if (epfd == 0) { PMSG ("Sprockets watchdog failed to initialize epoll. Exiting now.\n"); exit (EXIT_FAILURE); } int server_fd = NULL; if (port != NULL) { server_fd = sprocket_tcp_server (port, NULL); if (server_fd == 0) { PMSG ("Couldn't start watchdog server\n"); exit (EXIT_FAILURE); } if (add_fd_to_epoll (epfd, server_fd) == 0) { PERR ("Couldn't add watchdog server to epoll\n"); exit (EXIT_FAILURE); } } close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); syslog (LOG_NOTICE, "Sprockets watchdog successfully started\n"); int paused_for_signal = 0; char* stats = NULL; auto_string* stat_buffer = NULL; pthread_mutex_t stats_mutex; pthread_mutex_init(&stats_mutex, NULL); auto_array* thread_array = auto_array_create (10); if (thread_array == NULL) { syslog (LOG_CRIT, "Unable to create thread array - out of memory"); exit (EXIT_FAILURE); } while (1) { struct epoll_event events[MAX_EPOLL_EVENTS]; int num_fd = epoll_wait(epfd, events, MAX_EPOLL_EVENTS, 500); if (num_fd == -1) { if (errno == EINTR) { syslog (LOG_NOTICE, "epoll_wait interrupted. Continuing\n"); continue; } syslog (LOG_CRIT, "epoll_wait error: %s\n", strerror (errno)); exit (EXIT_FAILURE); } if (num_fd != 0) { // no fds timeout occurred for (int i = 0; i < num_fd; ++i) { if (events[i].data.fd == sfd) { // caught signal struct signalfd_siginfo fdsi; int s = read (sfd, &fdsi, sizeof fdsi); if (s != sizeof fdsi) { syslog (LOG_CRIT, "Read signal error: %s\n", strerror (errno)); continue; } switch (fdsi.ssi_signo) { case SIGINT: syslog (LOG_NOTICE, "Caught SIGINT - pausing\n"); paused_for_signal = 1; break; case SIGQUIT: syslog (LOG_NOTICE, "Caught SIGQUIT - exiting\n"); for (int ii = 0; ii < num_pids; ++ii) { if (pids[ii] != 0) { kill (pids[ii], SIGTERM); } } for (int ii = 0; ii < thread_array->count; ++ii) { watchdog_thread* wt = auto_array_get (thread_array, ii); char ex[2] = "EX"; write (wt->pipe_write, ex, 2); auto_array_delete (thread_array, free); } exit (EXIT_SUCCESS); case SIGHUP: syslog (LOG_NOTICE, "Caught SIGHUP\n"); paused_for_signal = 0; break; case SIGCHLD: syslog (LOG_NOTICE, "Caught SIGCHLD\n"); break; default: syslog (LOG_NOTICE, "Caught unknown signal\n"); break; } } else if (events[i].data.fd == server_fd) { struct sockaddr_in addr; socklen_t addr_sz = 0; int client_fd = accept (server_fd, (struct sockaddr*) &addr, &addr_sz); watchdog_thread_args* thread_args = malloc (sizeof thread_args); if (thread_args == NULL) { syslog (LOG_CRIT, "Malloc returned NULL: %s", strerror (errno)); exit (EXIT_FAILURE); } watchdog_thread* dog_thread = malloc (sizeof dog_thread); if (dog_thread == NULL) { syslog (LOG_CRIT, "Malloc returned NULL: %s", strerror (errno)); exit (EXIT_FAILURE); } int pipefd[2]; if (pipe (pipefd) < 0) { syslog (LOG_CRIT, "watchdog pipe error: %s", strerror (errno)); continue; } dog_thread->pipe_write = pipefd[1]; thread_args->pipe_read = pipefd[0]; thread_args->client_fd = client_fd; thread_args->stats = &stats; thread_args->stats_mutex = &stats_mutex; pthread_attr_t attr; int trv = 0; if ((trv = pthread_attr_init (&attr)) != 0) { syslog (LOG_CRIT, "pthread_attr_init: %s\n", strerror (trv)); continue; } if ((trv = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) != 0) { syslog (LOG_CRIT, "pthread_attr_setdetachstate: %s\n", strerror (trv)); continue; } if ((trv = pthread_create(&dog_thread->th_id, &attr, client_thread, thread_args)) != 0) { syslog (LOG_CRIT, "pthread_create: %s\n", strerror (trv)); continue; } auto_array_add (thread_array, dog_thread); pthread_attr_destroy(&attr); } } } if (paused_for_signal) { syslog (LOG_NOTICE, "Paused for signal\n"); } else { auto_array* stat_files = auto_array_create (num_pids); for (int i = 0; i < num_pids; ++i) { if (pids[i] == 0) { continue; } char pid[32]; sprintf (pid, "%d", pids[i]); FILE* p = get_stat_filep (pid); if (p == NULL) { syslog (LOG_CRIT, "Process with pid %s has halted", pid); if (email_address != NULL && mail_server != NULL) { char msg[2048]; snprintf (msg, 2048, email_alert_msg_format, email_address, email_address, pid); send_email (mail_server, email_address, email_address, msg); pids[i] = 0; } continue; } auto_array_add (stat_files, p); } pthread_mutex_lock(&stats_mutex); if (stat_buffer != NULL) { auto_string_delete (stat_buffer); } stat_buffer = auto_string_create (1024); if (stat_buffer == NULL) { syslog (LOG_CRIT, "Unable to create stat buffer - out of memory"); exit (EXIT_FAILURE); } for (int i = 0; i < stat_files->count; ++i) { FILE* f = auto_array_get (stat_files, i); char* tmp = get_proc_string (f); if (tmp != NULL) { auto_string_append (stat_buffer, tmp); free (tmp); } } stats = stat_buffer->buf; pthread_mutex_unlock (&stats_mutex); for (int i = 0; i < thread_array->count; ++i) { watchdog_thread* wt = auto_array_get (thread_array, i); char ok[2] = "OK"; if (write (wt->pipe_write, ok, 2) <= 0) { syslog (LOG_CRIT, "watchdog write client thread: %s", strerror (errno)); auto_array_remove (thread_array, i); close (wt->pipe_write); free (wt); } } auto_array_delete (stat_files, close_file); } } } return pid; }
static void ICACHE_FLASH_ATTR loop(os_event_t* events) { if (!initFinished) { // loop by adding this function to the task queue system_os_post(user_procTaskPrio, 0, 0); if(is_wifi_connected()) { user_init2(); initFinished = true; } return; } static bool pendingEmailAlert = false; // check unprocessed OOK packets to see if there are any newly // triggered sensors bool newTriggerings = false; while(packets_available(&unprocessedPackets)) { uint32 packet = packet_pop(&unprocessedPackets); char* source = my_strdup(ook_ID_to_name(packet)); // check if the current packet is a new triggering bool packetIsNewTriggering = true; #ifdef PRINT_OOK_PACKETS_DEBUG os_printf("%x\r\n", packet); #endif // check for the key fob signals for arming/disarming if (packet == ARM_CODE) arm_alarm(); else if (packet == DISARM_CODE) disarm_alarm(); // must be some other code, or invalid else if (source != NULL && alarmArmed) { int i, j; // ensure that an already-triggered sensor is not duplicated in list for (i = 0; i < triggeredSensorsIter; i++) { if (triggeredSensorsNames[i] != NULL) for (j = 0; source[j] == triggeredSensorsNames[i][j]; j++) { // reached the end of both strings and they've been the // same all along if (source[j] == '\0') packetIsNewTriggering = false; } } if (packetIsNewTriggering) { triggeredSensorsNames[triggeredSensorsIter] = source; triggeredSensorsTimestamps[triggeredSensorsIter] = sntp_get_current_timestamp(); triggeredSensorsIter += 1; newTriggerings = true; } else os_free(source); } } if (newTriggerings) { updateWebpage(); pendingEmailAlert = true; } // checked so that a pending email alert is cancelled if the "disarm" button is pressed after a // sensor has been triggered if(!alarmArmed) pendingEmailAlert = false; if (pendingEmailAlert) { if (triggeredSensorsIter > 0 && sntp_get_current_timestamp() - triggeredSensorsTimestamps[0] > ALERT_EMAIL_DELAY) { generate_email_body(); send_email("ESP8266 Alarm", generatedEmailBody); #ifdef PRINT_EMAIL_DEBUG os_printf("trying to send email\n"); #endif pendingEmailAlert = false; } } // loop by adding this function to the task queue system_os_post(user_procTaskPrio, 0, 0); }
int batch_mail(int conn, char *command) { char instance[63] = ""; int business = 0; row_t *rows = NULL; row_t *row = NULL; row_t *rr = NULL; int rowc; int count = 0; int flags = 0; char *sql; char *email = NULL; char *file; char *filename; char *tmp = NULL; smtp_recipient_t *r = NULL; smtp_header_t *h = NULL; smtp_attach_t *a = NULL; if (sscanf(command, "MAIL %[^.].%i\n", instance, &business) != 2) { chat(conn, "ERROR: Invalid syntax\n"); return 0; } chat(conn, "Sending email batch for instance '%s', business '%i' ... ", instance, business); db_connect(config->dbs); /* verify instance and business exist */ asprintf(&sql, "SELECT * FROM instance WHERE id='%s';", instance); rowc = batch_fetch_rows(NULL, 0, sql, &rows); free(sql); if (rowc == 0) { chat(conn, "ERROR: instance '%s' does not exist\n", instance); db_disconnect(config->dbs); return 0; } rows = NULL; asprintf(&sql, "SELECT * FROM business WHERE id='%i';", business); rowc = batch_fetch_rows(instance, 0, sql, &rows); free(sql); if (rowc == 0) { chat(conn, "ERROR: business '%s.%i' does not exist\n", instance, business); db_disconnect(config->dbs); return 0; } rows = NULL; chat(conn, CLERK_RESP_OK); /* lock emaildetail table */ batch_exec_sql(instance, business, "BEGIN WORK; LOCK TABLE emaildetail IN EXCLUSIVE MODE"); /* fetch emails to send */ rowc = batch_fetch_rows(instance, business, "SELECT * FROM email_unsent", &rows); row = rows; while (row != NULL) { /* get id of email */ email = db_field(row, "email")->fvalue; if (email == NULL) continue; /* loop through recipients */ asprintf(&sql, "SELECT * FROM emailrecipient WHERE email=%s", email); rowc = batch_fetch_rows(instance, business, sql, &rr); free(sql); if (rowc == 0) { /* skip email with no recipients */ syslog(LOG_DEBUG, "Skipping email with no recipients"); row = row->next; continue; } flags = 0; while (rr != NULL) { if (strcmp(db_field(rr, "is_to")->fvalue, "t") == 0) flags += EMAIL_TO; if (strcmp(db_field(rr, "is_cc")->fvalue, "t") == 0) flags += EMAIL_CC; add_recipient(&r, "", db_field(rr, "emailaddress")->fvalue, flags); rr = rr->next; } /* loop through headers */ asprintf(&sql, "SELECT * FROM emailheader WHERE email=%s", email); rowc = batch_fetch_rows(instance, business, sql, &rr); free(sql); while (rr != NULL) { add_header(&h, db_field(rr, "header")->fvalue, db_field(rr, "value")->fvalue); rr = rr->next; } /* loop through attachments */ asprintf(&sql, "SELECT * FROM emailpart WHERE email=%s", email); rowc = batch_fetch_rows(instance, business, sql, &rr); free(sql); while (rr != NULL) { file = db_field(rr, "file")->fvalue; tmp = strdup(file); filename = basename(tmp); add_attach(&a, file, filename); free(tmp); rr = rr->next; } /* send email */ /* FIXME: this will quietly crash if db_field returns NULL */ if (send_email( db_field(row, "sendername")->fvalue, db_field(row, "sendermail")->fvalue, db_field(row, "body")->fvalue, r, h, a) == 0) { /* update email with sent time */ asprintf(&sql, "SELECT email_sent(%s);", email); chat(conn, "sql: %s\n", sql); batch_exec_sql(instance, business, sql); free(sql); count++; } free_recipient(r); r = NULL; free_header(h); h = NULL; free_attach(a); a = NULL; row = row->next; } /* commit changes and unlock emaildetail table */ batch_exec_sql(instance, business, "COMMIT WORK;"); db_disconnect(config->dbs); chat(conn, "%i/%i emails sent\n", count, rowc); return 0; }
/****************************************************************************** * * * Function: execute_action * * * * Purpose: execute an action depending on mediatype * * * * Parameters: alert - alert details * * mediatype - media details * * * * Return value: SUCCESS - action executed successfully * * FAIL - otherwise, error will contain error message * * * * Author: Alexei Vladishev * * * ******************************************************************************/ int execute_action(DB_ALERT *alert, DB_MEDIATYPE *mediatype, char *error, int max_error_len) { const char *__function_name = "execute_action"; int res = FAIL; zabbix_log(LOG_LEVEL_DEBUG, "In %s(): alertid [" ZBX_FS_UI64 "] mediatype [%d]", __function_name, alert->alertid, mediatype->type); if (MEDIA_TYPE_EMAIL == mediatype->type) { res = send_email(mediatype->smtp_server, mediatype->smtp_port, mediatype->smtp_helo, mediatype->smtp_email, alert->sendto, alert->subject, alert->message, mediatype->smtp_security, mediatype->smtp_verify_peer, mediatype->smtp_verify_host, mediatype->smtp_authentication, mediatype->username, mediatype->passwd, ALARM_ACTION_TIMEOUT, error, max_error_len); } #ifdef HAVE_JABBER else if (MEDIA_TYPE_JABBER == mediatype->type) { /* Jabber uses its own timeouts */ res = send_jabber(mediatype->username, mediatype->passwd, alert->sendto, alert->subject, alert->message, error, max_error_len); } #endif else if (MEDIA_TYPE_SMS == mediatype->type) { /* SMS uses its own timeouts */ res = send_sms(mediatype->gsm_modem, alert->sendto, alert->message, error, max_error_len); } else if (MEDIA_TYPE_EZ_TEXTING == mediatype->type) { /* Ez Texting uses its own timeouts */ res = send_ez_texting(mediatype->username, mediatype->passwd, alert->sendto, alert->message, mediatype->exec_path, error, max_error_len); } else if (MEDIA_TYPE_EXEC == mediatype->type) { char *cmd = NULL, *send_to, *subject, *message, *output = NULL; size_t cmd_alloc = ZBX_KIBIBYTE, cmd_offset = 0; cmd = zbx_malloc(cmd, cmd_alloc); zbx_snprintf_alloc(&cmd, &cmd_alloc, &cmd_offset, "%s/%s", CONFIG_ALERT_SCRIPTS_PATH, mediatype->exec_path); if (0 == access(cmd, X_OK)) { send_to = zbx_dyn_escape_shell_single_quote(alert->sendto); subject = zbx_dyn_escape_shell_single_quote(alert->subject); message = zbx_dyn_escape_shell_single_quote(alert->message); zbx_snprintf_alloc(&cmd, &cmd_alloc, &cmd_offset, " '%s' '%s' '%s'", send_to, subject, message); zbx_free(message); zbx_free(subject); zbx_free(send_to); if (SUCCEED == (res = zbx_execute(cmd, &output, error, max_error_len, ALARM_ACTION_TIMEOUT))) { zabbix_log(LOG_LEVEL_DEBUG, "%s output:\n%s", mediatype->exec_path, output); zbx_free(output); } else res = FAIL; } else zbx_snprintf(error, max_error_len, "%s: %s", cmd, zbx_strerror(errno)); zbx_free(cmd); } else { zbx_snprintf(error, max_error_len, "unsupported media type [%d]", mediatype->type); zabbix_log(LOG_LEVEL_ERR, "alert ID [" ZBX_FS_UI64 "]: %s", alert->alertid, error); } zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(res)); return res; }
namespace wfc { namespace { static CursesWindow* CreateBoxedWindow(const std::string& title, int nlines, int ncols, int y, int x) { unique_ptr<CursesWindow> window(new CursesWindow(out->window(), out->color_scheme(), nlines, ncols, y, x)); window->SetColor(SchemeId::WINDOW_BOX); window->Box(0, 0); window->SetTitle(title); window->SetColor(SchemeId::WINDOW_TEXT); return window.release(); } } auto noop = [](){}; static void wfc_command(int instance_location_id, std::function<void()> f, std::function<void()> f2 = noop, std::function<void()> f3 = noop, std::function<void()> f4 = noop) { session()->reset_local_io(new CursesLocalIO(out->window()->GetMaxY())); wfc_cls(); write_inst(instance_location_id, 0, INST_FLAGS_NONE); f(); f2(); f3(); f4(); write_inst(INST_LOC_WFC, 0, INST_FLAGS_NONE); } auto send_email_f = []() { session()->usernum = 1; bout << "|#1Send Email:"; send_email(); session()->WriteCurrentUser(1); }; auto view_sysop_log_f = []() { unique_ptr<WStatus> pStatus(session()->status_manager()->GetStatus()); const string sysop_log_file = GetSysopLogFileName(date()); print_local_file(sysop_log_file); }; auto view_yesterday_sysop_log_f = []() { unique_ptr<WStatus> pStatus(session()->status_manager()->GetStatus()); print_local_file(pStatus->GetLogFileName(1)); }; auto read_mail_f = []() { session()->usernum = 1; readmail(0); session()->WriteCurrentUser(1); }; auto getkey_f = []() { getkey(); }; ControlCenter::ControlCenter() { const string title = StringPrintf("WWIV %s%s Server.", wwiv_version, beta_version); CursesIO::Init(title); // take ownership of out. out_scope_.reset(out); session()->SetWfcStatus(0); } ControlCenter::~ControlCenter() {} static void DrawCommands(CursesWindow* commands) { commands->SetColor(SchemeId::WINDOW_TEXT); commands->PutsXY(1, 1, "[B]oardEdit [C]hainEdit"); commands->PutsXY(1, 2, "[D]irEdit [E]mail [G]-FileEdit"); commands->PutsXY(1, 3, "[I]nit Voting Data [J] ConfEdit"); commands->PutsXY(1, 4, "Sysop[L]og Read [M]ail [N]etLog"); commands->PutsXY(1, 5, "[P]ending Net Data [/] Net Callout"); commands->PutsXY(1, 6, "[R]ead all email [S]ystem Status"); commands->PutsXY(1, 7, "[U]serEdit [Y]-Log [Z]-Log"); } static void DrawStatus(CursesWindow* statusWindow) { statusWindow->SetColor(SchemeId::WINDOW_TEXT); statusWindow->PutsXY(2, 1, "Today:"); statusWindow->PutsXY(2, 2, "Calls: XXXXX Minutes: XXXXX"); statusWindow->PutsXY(2, 3, "M: XXX L: XXX E: XXX F: XXX FW: XXX"); statusWindow->PutsXY(2, 4, "Totals:"); statusWindow->PutsXY(2, 5, "Users: XXXXX Calls: XXXXX"); statusWindow->PutsXY(2, 6, "Last User:"******"XXXXXXXXXXXXXXXXXXXXXXXXXX"); } static string GetLastUserName(int inst_num) { instancerec ir; get_inst_info(inst_num, &ir); if (ir.flags & INST_FLAGS_ONLINE) { return session()->names()->UserName(ir.user); } else { return "Nobody"; } } static void UpdateStatus(CursesWindow* statusWindow) { statusWindow->SetColor(SchemeId::WINDOW_DATA); std::unique_ptr<WStatus> pStatus(session()->status_manager()->GetStatus()); statusWindow->PrintfXY(9, 2, "%-5d", pStatus->GetNumCallsToday()); statusWindow->PrintfXY(24, 2, "%-5d", pStatus->GetMinutesActiveToday()); statusWindow->PrintfXY(5, 3, "%-3u", pStatus->GetNumMessagesPostedToday()); statusWindow->PrintfXY(12, 3, "%-3u", pStatus->GetNumLocalPosts()); statusWindow->PrintfXY(19, 3, "%-3u", pStatus->GetNumEmailSentToday()); statusWindow->PrintfXY(26, 3, "%-3u", pStatus->GetNumFeedbackSentToday()); fwaiting = session()->user()->GetNumMailWaiting(); statusWindow->PrintfXY(34, 3, "%-3d", fwaiting); statusWindow->PrintfXY(9, 5, "%-5d", pStatus->GetNumUsers()); statusWindow->PrintfXY(22, 5, "%-6lu", pStatus->GetCallerNumber()); // TODO(rushfan): Need to know the last used node number // then call GetLastUserName. // statusWindow->PutsXY(2, 7, "XXXXXXXXXXXXXXXXXXXXXXXXXX"); } static void CleanNetIfNeeded() { static int mult_time = 0; if (session()->IsCleanNetNeeded() || std::abs(timer1() - mult_time) > 1000L) { cleanup_net(); mult_time = timer1(); } } static void RunEventsIfNeeded() { unique_ptr<WStatus> pStatus(session()->status_manager()->GetStatus()); if (!IsEquals(date(), pStatus->GetLastDate())) { if ((session()->GetBeginDayNodeNumber() == 0) || (session()->instance_number() == session()->GetBeginDayNodeNumber())) { cleanup_events(); beginday(true); } } if (!do_event) { check_event(); } while (do_event) { run_event(do_event - 1); check_event(); } session()->SetCurrentSpeed("KB"); static time_t last_time_c = 0; time_t lCurrentTime = time(nullptr); if ((((rand() % 8000) == 0) || (lCurrentTime - last_time_c > 1200)) && net_sysnum) { lCurrentTime = last_time_c; attempt_callout(); } } void ControlCenter::Initialize() { // Initialization steps that have to happen before we // have a functional WFC system. This also supposes that // session()->InitializeBBS has been called. out->Cls(ACS_CKBOARD); const int logs_y_padding = 1; const int logs_start = 11; const int logs_length = out->window()->GetMaxY() - logs_start - logs_y_padding; log_.reset(new WfcLog(logs_length - 2)); commands_.reset(CreateBoxedWindow("Commands", 9, 38, 1, 1)); status_.reset(CreateBoxedWindow("Status", 9, 39, 1, 40)); logs_.reset(CreateBoxedWindow("Logs", logs_length, 78, 11, 1)); DrawCommands(commands_.get()); DrawStatus(status_.get()); vector<HelpItem> help_items0 = { { "?", "All Commands" },}; vector<HelpItem> help_items1 = { {"Q", "Quit" } }; out->footer()->ShowHelpItems(0, help_items0); out->footer()->ShowHelpItems(1, help_items1); session()->ReadCurrentUser(1); read_qscn(1, qsc, false); session()->ResetEffectiveSl(); session()->usernum = 1; fwaiting = session()->user()->GetNumMailWaiting(); session()->SetWfcStatus(1); } void ControlCenter::Run() { Initialize(); bool need_refresh = false; for (bool done = false; !done;) { if (need_refresh) { // refresh the window since we call endwin before invoking bbs code. RefreshAll(); need_refresh = false; } wtimeout(commands_->window(), 500); int key = commands_->GetChar(); if (key == ERR) { // we have a timeout. process other events need_refresh = false; UpdateLog(); UpdateStatus(status_.get()); CleanNetIfNeeded(); RunEventsIfNeeded(); continue; } need_refresh = true; session()->SetWfcStatus(2); // Call endwin since we'll be out of curses IO endwin(); switch (toupper(key)) { case 'B': wfc_command(INST_LOC_BOARDEDIT, boardedit, cleanup_net); log_->Put("Ran BoardEdit"); break; case 'C': wfc_command(INST_LOC_CHAINEDIT, chainedit); log_->Put("Ran ChainEdit"); break; case 'D': wfc_command(INST_LOC_DIREDIT, dlboardedit); log_->Put("Ran DirEdit"); break; case 'E': wfc_command(INST_LOC_EMAIL, send_email_f, cleanup_net); break; case 'G': wfc_command(INST_LOC_GFILEEDIT, gfileedit); break; case 'H': wfc_command(INST_LOC_EVENTEDIT, eventedit); break; case 'I': wfc_command(INST_LOC_VOTEEDIT, ivotes); break; case 'J': wfc_command(INST_LOC_CONFEDIT, edit_confs); break; case 'L': wfc_command(INST_LOC_WFC, view_sysop_log_f); break; case 'M': wfc_command(INST_LOC_EMAIL, read_mail_f, cleanup_net); break; case 'N': wfc_command(INST_LOC_WFC, []() { print_local_file("net.log"); }); break; case 'P': wfc_command(INST_LOC_WFC, print_pending_list); break; case 'R': wfc_command(INST_LOC_MAILR, mailr); break; case 'S': wfc_command(INST_LOC_WFC, prstatus, getkey_f); break; case 'U': wfc_command(INST_LOC_UEDIT, []() { uedit(1, UEDIT_NONE); } ); break; case 'Y': wfc_command(INST_LOC_WFC, view_yesterday_sysop_log_f); break; case 'Z': wfc_command(INST_LOC_WFC, zlog, getkey_f); break; case 'Q': done=true; break; // ansicallout doesn't work due to arrow keys and other drawing problems with it under curses. // case '/': wfc_command(INST_LOC_NET, []() { force_callout(0); }); log_->Put("Ran Network Callout"); break; case ' ': log_->Put("Not Implemented Yet"); break; } TouchAll(); } } void ControlCenter::TouchAll() { out->window()->TouchWin(); commands_->TouchWin(); status_->TouchWin(); logs_->TouchWin(); } void ControlCenter::RefreshAll() { out->window()->Refresh(); commands_->Refresh(); status_->Refresh(); logs_->Refresh(); UpdateStatus(status_.get()); } void ControlCenter::UpdateLog() { if (!log_->dirty()) { return; } vector<string> lines; if (!log_->Get(lines)) { return; } int start = 1; const int width = logs_->GetMaxX() - 4; for (const auto& line : lines) { logs_->PutsXY(1, start, line); logs_->PutsXY(1 + line.size(), start, string(width - line.size(), ' ')); start++; } } }
/*** send smail to the email ccount ***/ void forward_email(char *name, char *from, char *message) { FILE *fp; UR_OBJECT u; char fname[FNAME_LEN]; int on=0; set_crash(); if (!amsys->forwarding) return; if ((u=get_user(name))) { on=1; goto SKIP; } /* Have to create temp user if not logged on to check if email verified, etc */ if ((u=create_user())==NULL) { write_syslog(ERRLOG,1,"Unable to create temporary user object in forward_email().\n"); return; } strcpy(u->name,name); if (!load_user_details(u)) { destruct_user(u); destructed=0; return; } on=0; SKIP: if (!u->mail_verified) { if (!on) { destruct_user(u); destructed=0; } return; } if (!u->autofwd){ if (!on) { destruct_user(u); destructed=0; } return; } sprintf(fname,"%s/%s.FWD",MAILSPOOL,u->name); if (!(fp=fopen(fname,"w"))) { write_syslog(SYSLOG,0,"Unable to open forward mail file in set_forward_email()\n"); return; } fprintf(fp,"From: %s\n",reg_sysinfo[TALKERNAME]); fprintf(fp,"To: %s <%s>\n\n",u->name,u->email); from=colour_com_strip(from); fputs(from,fp); fputs("\n",fp); message=colour_com_strip(message); fputs(message,fp); fputs("\n\n",fp); fputs(talker_signature,fp); fclose(fp); send_email(u->email, "Auto-forward of smail", fname); write_syslog(SYSLOG,1,"%s had mail sent to their email address.\n",u->name); if (!on) { destruct_user(u); destructed=0; } return; }
/****************************************************************************** * * * Function: execute_action * * * * Purpose: execute an action depending on mediatype * * * * Parameters: alert - alert details * * mediatype - media details * * * * Return value: SUCCESS - action executed sucessfully * * FAIL - otherwise, error will contain error message * * * * Author: Alexei Vladishev * * * * Comments: * * * ******************************************************************************/ int execute_action(DB_ALERT *alert, DB_MEDIATYPE *mediatype, char *error, int max_error_len) { const char *__function_name = "execute_action"; int pid, res = FAIL; char full_path[MAX_STRING_LEN]; zabbix_log(LOG_LEVEL_DEBUG, "In %s(): alertid [" ZBX_FS_UI64 "] mediatype [%d]", __function_name, alert->alertid, mediatype->type); if (MEDIA_TYPE_EMAIL == mediatype->type) { alarm(40); res = send_email(mediatype->smtp_server, mediatype->smtp_helo, mediatype->smtp_email, alert->sendto, alert->subject, alert->message, error, max_error_len); alarm(0); } #if defined(HAVE_JABBER) else if (MEDIA_TYPE_JABBER == mediatype->type) { /* Jabber uses its own timeouts */ res = send_jabber(mediatype->username, mediatype->passwd, alert->sendto, alert->subject, alert->message, error, max_error_len); } #endif else if (MEDIA_TYPE_SMS == mediatype->type) { /* SMS uses its own timeouts */ res = send_sms(mediatype->gsm_modem, alert->sendto, alert->message, error, max_error_len); } else if (MEDIA_TYPE_EZ_TEXTING == mediatype->type) { /* Ez Texting uses its own timeouts */ res = send_ez_texting(mediatype->username, mediatype->passwd, alert->sendto, alert->message, mediatype->exec_path, error, max_error_len); } else if (MEDIA_TYPE_EXEC == mediatype->type) { pid = zbx_fork(); if (0 != pid) { waitpid(pid, NULL, 0); res = SUCCEED; } else { zbx_snprintf(full_path, sizeof(full_path), "%s/%s", CONFIG_ALERT_SCRIPTS_PATH, mediatype->exec_path); zabbix_log(LOG_LEVEL_DEBUG, "Before executing [%s]", full_path); if (-1 == execl(full_path, mediatype->exec_path, alert->sendto, alert->subject, alert->message, (char *)NULL)) { zabbix_log(LOG_LEVEL_ERR, "Error executing [%s] [%s]", full_path, strerror(errno)); zabbix_syslog("Error executing [%s] [%s]", full_path, strerror(errno)); exit(FAIL); } else THIS_SHOULD_NEVER_HAPPEN; } } else { zabbix_log(LOG_LEVEL_ERR, "Unsupported media type [%d] for alert ID [" ZBX_FS_UI64 "]", mediatype->type, alert->alertid); zabbix_syslog("Unsupported media type [%d] for alert ID [" ZBX_FS_UI64 "]", mediatype->type, alert->alertid); zbx_snprintf(error, max_error_len, "Unsupported media type [%d]", mediatype->type); res = FAIL; } zabbix_log(LOG_LEVEL_DEBUG, "End of %s(): %d", __function_name, zbx_result_string(res)); return res; }
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { CoInitializeEx(NULL, COINIT_MULTITHREADED); aslog::openlog(); aslog::setlevel(aslog::level::debug); curl_global_init(CURL_GLOBAL_ALL); load_settings(); HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pImagingFactory) ); hr = find_output(); CComPtr<IDXGIOutputDuplication> pDup; std::mt19937 rand(std::chrono::high_resolution_clock::now().time_since_epoch().count()); while (true) { Sleep((rand() % 30 + 1) * 60000 + (rand() % 30 + 1) * 1000); DXGI_OUTDUPL_FRAME_INFO frameInfo; CComPtr<IDXGIResource> pResource; if (!pDup) { hr = g_pOutput->DuplicateOutput(g_pDevice, &pDup); // First image captured is always black hr = pDup->AcquireNextFrame(1000, &frameInfo, &pResource); pDup->ReleaseFrame(); pResource.Release(); } hr = pDup->AcquireNextFrame(1000, &frameInfo, &pResource); if (hr == DXGI_ERROR_ACCESS_LOST) { pDup.Release(); continue; } else if (FAILED(hr)) { aslog::error(L"Unable to capture frame: 0x%.8x", hr); Sleep(1000); continue; } else { aslog::info(L"Captured frame successfully"); DWORD sz; UINT8 *data, *jpeg_data; UINT width, height; get_screen_data(pResource, &data, &width, &height); pResource.Release(); pDup->ReleaseFrame(); encode_jpeg(data, width, height, &jpeg_data, &sz); delete[] data; send_email(jpeg_data, sz); delete[] jpeg_data; } } aslog::closelog(); return 0; }
/****************************************************************************** * * * Function: execute_action * * * * Purpose: execute an action depending on mediatype * * * * Parameters: alert - alert details * * mediatype - media details * * * * Return value: SUCCESS - action executed sucessfully * * FAIL - otherwise, error will contain error message * * * * Author: Alexei Vladishev * * * * Comments: * * * ******************************************************************************/ int execute_action(DB_ALERT *alert,DB_MEDIATYPE *mediatype, char *error, int max_error_len) { int res=FAIL; int pid; char full_path[MAX_STRING_LEN]; char env_alertid[128],env_actionid[128],env_clock[128],env_mediatypeid[128], env_status[128]; char *zbxenv[] = { (char *)&env_alertid, (char *)&env_actionid, (char *)&env_clock, (char *)&env_mediatypeid, (char *)&env_status, (char *)0 }; zabbix_log( LOG_LEVEL_DEBUG, "In execute_action(%s)", mediatype->smtp_server); if(mediatype->type==MEDIA_TYPE_EMAIL) { alarm(40); res = send_email(mediatype->smtp_server,mediatype->smtp_helo,mediatype->smtp_email,alert->sendto,alert->subject, alert->message, error, max_error_len); alarm(0); } #if defined (HAVE_JABBER) else if(mediatype->type==MEDIA_TYPE_JABBER) { /* Jabber uses its own timeouts */ res = send_jabber(mediatype->username, mediatype->passwd, alert->sendto, alert->subject, alert->message, error, max_error_len); } #endif /* HAVE_JABBER */ else if(mediatype->type==MEDIA_TYPE_SMS) { /* SMS uses its own timeouts */ res = send_sms(mediatype->gsm_modem,alert->sendto,alert->message, error, max_error_len); } else if(mediatype->type==MEDIA_TYPE_EXEC) { /* if(-1 == execl(CONFIG_ALERT_SCRIPTS_PATH,mediatype->exec_path,alert->sendto,alert->subject,alert->message))*/ zabbix_log( LOG_LEVEL_DEBUG, "Before execl([%s],[%s])", CONFIG_ALERT_SCRIPTS_PATH, mediatype->exec_path); /* if(-1 == execl("/home/zabbix/bin/lmt.sh","lmt.sh",alert->sendto,alert->subject,alert->message,(char *)0))*/ pid = zbx_fork(); if(0 != pid) { waitpid(pid,NULL,0); } else { strscpy(full_path,CONFIG_ALERT_SCRIPTS_PATH); zbx_strlcat(full_path,"/",MAX_STRING_LEN); zbx_strlcat(full_path,mediatype->exec_path,MAX_STRING_LEN); ltrim_spaces(full_path); zabbix_log( LOG_LEVEL_DEBUG, "Before executing [%s]", full_path); zbx_snprintf(env_alertid,127,"ZABBIX_ALERT_ID=%d", alert->alertid); zbx_snprintf(env_actionid,127,"ZABBIX_ACTION_ID=%d", alert->actionid); zbx_snprintf(env_clock,127,"ZABBIX_ALERT_TIME=%d", alert->clock); zbx_snprintf(env_mediatypeid,127,"ZABBIX_ALERT_MEDIATYPEID=%d", alert->mediatypeid); zbx_snprintf(env_status,127,"ZABBIX_ALERT_STATUS=%d", alert->status); /* if(-1 == execl(full_path,mediatype->exec_path,alert->sendto,alert->subject,alert->message,(char *)0))*/ if(-1 == execle(full_path,mediatype->exec_path,alert->sendto,alert->subject,alert->message,(char *)0, zbxenv)) { zabbix_log( LOG_LEVEL_ERR, "Error executing [%s] [%s]", full_path, strerror(errno)); zabbix_syslog("Error executing [%s] [%s]", full_path, strerror(errno)); zbx_snprintf(error,max_error_len,"Error executing [%s] [%s]", full_path, strerror(errno)); res = FAIL; } else { res = SUCCEED; } /* In normal case the program will never reach this point */ zabbix_log( LOG_LEVEL_DEBUG, "After execl()"); exit(0); } res = SUCCEED; } else { zabbix_log( LOG_LEVEL_ERR, "Unsupported media type [%d] for alert ID [%d]", mediatype->type, alert->alertid); zabbix_syslog("Unsupported media type [%d] for alert ID [%d]", mediatype->type, alert->alertid); zbx_snprintf(error,max_error_len,"Unsupported media type [%d]", mediatype->type); res=FAIL; } zabbix_log( LOG_LEVEL_DEBUG, "End execute_action()"); return res; }
/****************************************************************************** * * * Function: execute_action * * * * Purpose: execute an action depending on mediatype * * * * Parameters: alert - alert details * * mediatype - media details * * * * Return value: SUCCESS - action executed sucessfully * * FAIL - otherwise, error will contain error message * * * * Author: Alexei Vladishev * * * ******************************************************************************/ int execute_action(DB_ALERT *alert, DB_MEDIATYPE *mediatype, char *error, int max_error_len) { const char *__function_name = "execute_action"; int res = FAIL; zabbix_log(LOG_LEVEL_DEBUG, "In %s(): alertid [" ZBX_FS_UI64 "] mediatype [%d]", __function_name, alert->alertid, mediatype->type); if (MEDIA_TYPE_EMAIL == mediatype->type) { alarm(ALARM_ACTION_TIMEOUT); res = send_email(mediatype->smtp_server, mediatype->smtp_helo, mediatype->smtp_email, alert->sendto, alert->subject, alert->message, error, max_error_len); alarm(0); } #ifdef HAVE_JABBER else if (MEDIA_TYPE_JABBER == mediatype->type) { /* Jabber uses its own timeouts */ res = send_jabber(mediatype->username, mediatype->passwd, alert->sendto, alert->subject, alert->message, error, max_error_len); } #endif else if (MEDIA_TYPE_SMS == mediatype->type) { /* SMS uses its own timeouts */ res = send_sms(mediatype->gsm_modem, alert->sendto, alert->message, error, max_error_len); } else if (MEDIA_TYPE_EZ_TEXTING == mediatype->type) { /* Ez Texting uses its own timeouts */ res = send_ez_texting(mediatype->username, mediatype->passwd, alert->sendto, alert->message, mediatype->exec_path, error, max_error_len); } else if (MEDIA_TYPE_EXEC == mediatype->type) { char full_path[MAX_STRING_LEN], *send_to, *subject, *message, *output = NULL; send_to = zbx_dyn_escape_string(alert->sendto, "\"\\"); subject = zbx_dyn_escape_string(alert->subject, "\"\\"); message = zbx_dyn_escape_string(alert->message, "\"\\"); zbx_snprintf(full_path, sizeof(full_path), "%s/%s \"%s\" \"%s\" \"%s\"", CONFIG_ALERT_SCRIPTS_PATH, mediatype->exec_path, send_to, subject, message); zbx_free(send_to); zbx_free(subject); zbx_free(message); if (SUCCEED == (res = zbx_execute(full_path, &output, error, max_error_len, ALARM_ACTION_TIMEOUT))) { zabbix_log(LOG_LEVEL_DEBUG, "%s output:\n%s", mediatype->exec_path, output); zbx_free(output); } else res = FAIL; } else { zbx_snprintf(error, max_error_len, "unsupported media type [%d]", mediatype->type); zabbix_log(LOG_LEVEL_ERR, "alert ID [" ZBX_FS_UI64 "]: %s", alert->alertid, error); zabbix_syslog("alert ID [" ZBX_FS_UI64 "]: %s", alert->alertid, error); } zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(res)); return res; }