uschar * tls_field_from_dn(uschar * dn, const uschar * mod) { int insep = ','; uschar outsep = '\n'; uschar * ele; uschar * match = NULL; int len; uschar * list = NULL; while ((ele = string_nextinlist(&mod, &insep, NULL, 0))) if (ele[0] != '>') match = ele; /* field tag to match */ else if (ele[1]) outsep = ele[1]; /* nondefault output separator */ dn_to_list(dn); insep = ','; len = match ? Ustrlen(match) : -1; while ((ele = string_nextinlist(CUSS &dn, &insep, NULL, 0))) if ( !match || Ustrncmp(ele, match, len) == 0 && ele[len] == '=' ) list = string_append_listele(list, outsep, ele+len+1); return list; }
static pcre_list * compile(const uschar * list) { int sep = 0; uschar *regex_string; const char *pcre_error; int pcre_erroffset; pcre_list *re_list_head = NULL; pcre_list *ri; /* precompile our regexes */ while ((regex_string = string_nextinlist(&list, &sep, NULL, 0))) if (strcmpic(regex_string, US"false") != 0 && Ustrcmp(regex_string, "0") != 0) { pcre *re; /* compile our regular expression */ if (!(re = pcre_compile( CS regex_string, 0, &pcre_error, &pcre_erroffset, NULL ))) { log_write(0, LOG_MAIN, "regex acl condition warning - error in regex '%s': %s at offset %d, skipped.", regex_string, pcre_error, pcre_erroffset); continue; } ri = store_get(sizeof(pcre_list)); ri->re = re; ri->pcre_text = regex_string; ri->next = re_list_head; re_list_head = ri; } return re_list_head; }
static int ibase_find(void *handle, uschar * filename, uschar * query, int length, uschar ** result, uschar ** errmsg, uint *do_cache) { int sep = 0; uschar *server; uschar *list = ibase_servers; uschar buffer[512]; /* Keep picky compilers happy */ do_cache = do_cache; DEBUG(D_lookup) debug_printf("Interbase query: %s\n", query); while ((server = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL) { BOOL defer_break = FALSE; int rc = perform_ibase_search(query, server, result, errmsg, &defer_break); if (rc != DEFER || defer_break) return rc; } if (ibase_servers == NULL) *errmsg = US "no Interbase servers defined (ibase_servers option)"; return DEFER; }
uschar * string_domain_alabel_to_utf8(const uschar * alabel, uschar ** err) { #ifdef SUPPORT_I18N_2008 const uschar * label; int sep = '.'; gstring * g = NULL; while (label = string_nextinlist(&alabel, &sep, NULL, 0)) if ( string_is_alabel(label) && !(label = string_localpart_alabel_to_utf8_(label, err)) ) return NULL; else g = string_append_listele(g, '.', label); return string_from_gstring(g); #else uschar * s1, * s; int rc; if ( (rc = idna_to_unicode_8z8z(CCS alabel, CSS &s1, IDNA_USE_STD3_ASCII_RULES)) != IDNA_SUCCESS) { if (err) *err = US idna_strerror(rc); return NULL; } s = string_copy(s1); free(s1); return s; #endif }
static int oracle_find(void *handle, uschar *filename, uschar *query, int length, uschar **result, uschar **errmsg, uint *do_cache) { int sep = 0; uschar *server; uschar *list = oracle_servers; uschar buffer[512]; do_cache = do_cache; /* Placate picky compilers */ DEBUG(D_lookup) debug_printf("ORACLE query: %s\n", query); while ((server = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL) { BOOL defer_break; int rc = perform_oracle_search(query, server, result, errmsg, &defer_break); if (rc != DEFER || defer_break) return rc; } if (oracle_servers == NULL) *errmsg = "no ORACLE servers defined (oracle_servers option)"; return DEFER; }
int spf_process(const uschar **listptr, uschar *spf_envelope_sender, int action) { int sep = 0; const uschar *list = *listptr; uschar *spf_result_id; int rc = SPF_RESULT_PERMERROR; if (!(spf_server && spf_request)) /* no global context, assume temp error and skip to evaluation */ rc = SPF_RESULT_PERMERROR; else if (SPF_request_set_env_from(spf_request, CS spf_envelope_sender)) /* Invalid sender address. This should be a real rare occurrence */ rc = SPF_RESULT_PERMERROR; else { /* get SPF result */ if (action == SPF_PROCESS_FALLBACK) { SPF_request_query_fallback(spf_request, &spf_response, CS spf_guess); spf_result_guessed = TRUE; } else SPF_request_query_mailfrom(spf_request, &spf_response); /* set up expansion items */ spf_header_comment = US SPF_response_get_header_comment(spf_response); spf_received = US SPF_response_get_received_spf(spf_response); spf_result = US SPF_strresult(SPF_response_result(spf_response)); spf_smtp_comment = US SPF_response_get_smtp_comment(spf_response); rc = SPF_response_result(spf_response); } /* We got a result. Now see if we should return OK or FAIL for it */ DEBUG(D_acl) debug_printf("SPF result is %s (%d)\n", SPF_strresult(rc), rc); if (action == SPF_PROCESS_GUESS && (!strcmp (SPF_strresult(rc), "none"))) return spf_process(listptr, spf_envelope_sender, SPF_PROCESS_FALLBACK); while ((spf_result_id = string_nextinlist(&list, &sep, NULL, 0))) { BOOL negate, result; if ((negate = spf_result_id[0] == '!')) spf_result_id++; result = Ustrcmp(spf_result_id, spf_result_id_list[rc].name) == 0; if (negate != result) return OK; } /* no match */ return FAIL; }
int bmi_check_rule(uschar *base64_verdict, uschar *option_list) { BmiError err; BmiErrorLocation err_loc; BmiErrorType err_type; BmiVerdict *verdict = NULL; int rc = 0; uschar *rule_num; uschar *rule_ptr; uschar rule_buffer[32]; int sep = 0; /* no verdict -> no rule fired */ if (base64_verdict == NULL) return 0; /* create verdict from base64 string */ err = bmiCreateVerdictFromStr(CS base64_verdict, &verdict); if (bmiErrorIsFatal(err) == BMI_TRUE) { err_loc = bmiErrorGetLocation(err); err_type = bmiErrorGetType(err); log_write(0, LOG_PANIC, "bmi error [loc %d type %d]: bmiCreateVerdictFromStr() failed. [%s]", (int)err_loc, (int)err_type, base64_verdict); return 0; }; err = bmiVerdictError(verdict); if (bmiErrorIsFatal(err) == BMI_TRUE) { /* error -> no rule fired */ bmiFreeVerdict(verdict); return 0; } /* loop through numbers */ rule_ptr = option_list; while ((rule_num = string_nextinlist(&rule_ptr, &sep, rule_buffer, 32)) != NULL) { int rule_int = -1; /* try to translate to int */ (void)sscanf(rule_num, "%d", &rule_int); if (rule_int > 0) { debug_printf("checking rule #%d\n", rule_int); /* check if rule fired on the message */ if (bmiVerdictRuleFired(verdict, rule_int) == BMI_TRUE) { debug_printf("rule #%d fired\n", rule_int); rc = 1; break; }; }; }; bmiFreeVerdict(verdict); return rc; };
BOOL tls_is_name_for_cert(const uschar * namelist, void * cert) { uschar * altnames = tls_cert_subject_altname(cert, US"dns"); uschar * subjdn; uschar * certname; int cmp_sep = 0; uschar * cmpname; if ((altnames = tls_cert_subject_altname(cert, US"dns"))) { int alt_sep = '\n'; while ((cmpname = string_nextinlist(&namelist, &cmp_sep, NULL, 0))) { const uschar * an = altnames; while ((certname = string_nextinlist(&an, &alt_sep, NULL, 0))) if (is_name_match(cmpname, certname)) return TRUE; } } else if ((subjdn = tls_cert_subject(cert, NULL))) { int sn_sep = ','; dn_to_list(subjdn); while ((cmpname = string_nextinlist(&namelist, &cmp_sep, NULL, 0))) { const uschar * sn = subjdn; while ((certname = string_nextinlist(&sn, &sn_sep, NULL, 0))) if ( *certname++ == 'C' && *certname++ == 'N' && *certname++ == '=' && is_name_match(cmpname, certname) ) return TRUE; } } return FALSE; }
static BOOL set_priority(int *plist, int psize, uschar *s, pri_item *index, int isize, uschar *which) { int sep = 0; BOOL first = TRUE; uschar *t; while ((t = string_nextinlist(&s, &sep, big_buffer, big_buffer_size)) != NULL) { int i; BOOL exclude = t[0] == '!'; if (first && !exclude) plist[0] = 0; first = FALSE; for (i = 0; i < isize; i++) { uschar *ss = strstric(t, index[i].name, FALSE); if (ss != NULL) { uschar *endss = ss + Ustrlen(index[i].name); if ((ss == t || !isalnum(ss[-1])) && !isalnum(*endss)) { if (exclude) remove_priority(plist, index[i].values); else { if (!add_priority(plist, psize, index[i].values)) { log_write(0, LOG_MAIN|LOG_PANIC, "GnuTLS init failed: %s " "priority table overflow", which); return FALSE; } } } } } } DEBUG(D_tls) { int *ptr = plist; debug_printf("adjusted %s priorities:", which); while (*ptr != 0) debug_printf(" %d", *ptr++); debug_printf("\n"); } return TRUE; }
int spam(const uschar **listptr) { int sep = 0; const uschar *list = *listptr; uschar *user_name; uschar user_name_buffer[128]; unsigned long mbox_size; FILE *mbox_file; int spamd_sock = -1; uschar spamd_buffer[32600]; int i, j, offset, result; uschar spamd_version[8]; uschar spamd_short_result[8]; uschar spamd_score_char; double spamd_threshold, spamd_score, spamd_reject_score; int spamd_report_offset; uschar *p,*q; int override = 0; time_t start; size_t read, wrote; #ifndef NO_POLL_H struct pollfd pollfd; #else /* Patch posted by Erik ? for OS X */ struct timeval select_tv; /* and applied by PH */ fd_set select_fd; #endif uschar *spamd_address_work; spamd_address_container * sd; /* stop compiler warning */ result = 0; /* find the username from the option list */ if ((user_name = string_nextinlist(&list, &sep, user_name_buffer, sizeof(user_name_buffer))) == NULL) { /* no username given, this means no scanning should be done */ return FAIL; } /* if username is "0" or "false", do not scan */ if ( (Ustrcmp(user_name,"0") == 0) || (strcmpic(user_name,US"false") == 0) ) return FAIL; /* if there is an additional option, check if it is "true" */ if (strcmpic(list,US"true") == 0) /* in that case, always return true later */ override = 1; /* expand spamd_address if needed */ if (*spamd_address == '$') { spamd_address_work = expand_string(spamd_address); if (spamd_address_work == NULL) { log_write(0, LOG_MAIN|LOG_PANIC, "%s spamd_address starts with $, but expansion failed: %s", loglabel, expand_string_message); return DEFER; } } else spamd_address_work = spamd_address; DEBUG(D_acl) debug_printf("spamd: addrlist '%s'\n", spamd_address_work); /* check if previous spamd_address was expanded and has changed. dump cached results if so */ if ( spam_ok && prev_spamd_address_work != NULL && Ustrcmp(prev_spamd_address_work, spamd_address_work) != 0 ) spam_ok = 0; /* if we scanned for this username last time, just return */ if (spam_ok && Ustrcmp(prev_user_name, user_name) == 0) return override ? OK : spam_rc; /* make sure the eml mbox file is spooled up */ mbox_file = spool_mbox(&mbox_size, NULL); if (mbox_file == NULL) { /* error while spooling */ log_write(0, LOG_MAIN|LOG_PANIC, "%s error while creating mbox spool file", loglabel); return DEFER; } start = time(NULL); { int num_servers = 0; int current_server; uschar * address; const uschar * spamd_address_list_ptr = spamd_address_work; spamd_address_container * spamd_address_vector[32]; /* Check how many spamd servers we have and register their addresses */ sep = 0; /* default colon-sep */ while ((address = string_nextinlist(&spamd_address_list_ptr, &sep, NULL, 0)) != NULL) { const uschar * sublist; int sublist_sep = -(int)' '; /* default space-sep */ unsigned args; uschar * s; DEBUG(D_acl) debug_printf("spamd: addr entry '%s'\n", address); sd = (spamd_address_container *)store_get(sizeof(spamd_address_container)); for (sublist = address, args = 0, spamd_param_init(sd); (s = string_nextinlist(&sublist, &sublist_sep, NULL, 0)); args++ ) { DEBUG(D_acl) debug_printf("spamd: addr parm '%s'\n", s); switch (args) { case 0: sd->hostspec = s; if (*s == '/') args++; /* local; no port */ break; case 1: sd->hostspec = string_sprintf("%s %s", sd->hostspec, s); break; default: spamd_param(s, sd); break; } } if (args < 2) { log_write(0, LOG_MAIN, "%s warning - invalid spamd address: '%s'", loglabel, address); continue; } spamd_address_vector[num_servers] = sd; if (++num_servers > 31) break; } /* check if we have at least one server */ if (!num_servers) { log_write(0, LOG_MAIN|LOG_PANIC, "%s no useable spamd server addresses in spamd_address configuration option.", loglabel); goto defer; } current_server = spamd_get_server(spamd_address_vector, num_servers); sd = spamd_address_vector[current_server]; for(;;) { uschar * errstr; DEBUG(D_acl) debug_printf("spamd: trying server %s\n", sd->hostspec); for (;;) { if ( (spamd_sock = ip_streamsocket(sd->hostspec, &errstr, 5)) >= 0 || sd->retry <= 0 ) break; DEBUG(D_acl) debug_printf("spamd: server %s: retry conn\n", sd->hostspec); while (sd->retry > 0) sd->retry = sleep(sd->retry); } if (spamd_sock >= 0) break; log_write(0, LOG_MAIN, "%s spamd: %s", loglabel, errstr); sd->is_failed = TRUE; current_server = spamd_get_server(spamd_address_vector, num_servers); if (current_server < 0) { log_write(0, LOG_MAIN|LOG_PANIC, "%s all spamd servers failed", loglabel); goto defer; } sd = spamd_address_vector[current_server]; } } (void)fcntl(spamd_sock, F_SETFL, O_NONBLOCK); /* now we are connected to spamd on spamd_sock */ if (sd->is_rspamd) { /* rspamd variant */ uschar *req_str; const uschar * helo; const uschar * fcrdns; const uschar * authid; req_str = string_sprintf("CHECK RSPAMC/1.3\r\nContent-length: %lu\r\n" "Queue-Id: %s\r\nFrom: <%s>\r\nRecipient-Number: %d\r\n", mbox_size, message_id, sender_address, recipients_count); for (i = 0; i < recipients_count; i ++) req_str = string_sprintf("%sRcpt: <%s>\r\n", req_str, recipients_list[i].address); if ((helo = expand_string(US"$sender_helo_name")) != NULL && *helo != '\0') req_str = string_sprintf("%sHelo: %s\r\n", req_str, helo); if ((fcrdns = expand_string(US"$sender_host_name")) != NULL && *fcrdns != '\0') req_str = string_sprintf("%sHostname: %s\r\n", req_str, fcrdns); if (sender_host_address != NULL) req_str = string_sprintf("%sIP: %s\r\n", req_str, sender_host_address); if ((authid = expand_string(US"$authenticated_id")) != NULL && *authid != '\0') req_str = string_sprintf("%sUser: %s\r\n", req_str, authid); req_str = string_sprintf("%s\r\n", req_str); wrote = send(spamd_sock, req_str, Ustrlen(req_str), 0); } else { /* spamassassin variant */ (void)string_format(spamd_buffer, sizeof(spamd_buffer), "REPORT SPAMC/1.2\r\nUser: %s\r\nContent-length: %ld\r\n\r\n", user_name, mbox_size); /* send our request */ wrote = send(spamd_sock, spamd_buffer, Ustrlen(spamd_buffer), 0); } if (wrote == -1) { (void)close(spamd_sock); log_write(0, LOG_MAIN|LOG_PANIC, "%s spamd %s send failed: %s", loglabel, callout_address, strerror(errno)); goto defer; } /* now send the file */ /* spamd sometimes accepts conections but doesn't read data off * the connection. We make the file descriptor non-blocking so * that the write will only write sufficient data without blocking * and we poll the desciptor to make sure that we can write without * blocking. Short writes are gracefully handled and if the whole * trasaction takes too long it is aborted. * Note: poll() is not supported in OSX 10.2 and is reported to be * broken in more recent versions (up to 10.4). */ #ifndef NO_POLL_H pollfd.fd = spamd_sock; pollfd.events = POLLOUT; #endif (void)fcntl(spamd_sock, F_SETFL, O_NONBLOCK); do { read = fread(spamd_buffer,1,sizeof(spamd_buffer),mbox_file); if (read > 0) { offset = 0; again: #ifndef NO_POLL_H result = poll(&pollfd, 1, 1000); /* Patch posted by Erik ? for OS X and applied by PH */ #else select_tv.tv_sec = 1; select_tv.tv_usec = 0; FD_ZERO(&select_fd); FD_SET(spamd_sock, &select_fd); result = select(spamd_sock+1, NULL, &select_fd, NULL, &select_tv); #endif /* End Erik's patch */ if (result == -1 && errno == EINTR) goto again; else if (result < 1) { if (result == -1) log_write(0, LOG_MAIN|LOG_PANIC, "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno)); else { if (time(NULL) - start < sd->timeout) goto again; log_write(0, LOG_MAIN|LOG_PANIC, "%s timed out writing spamd %s, socket", loglabel, callout_address); } (void)close(spamd_sock); goto defer; } wrote = send(spamd_sock,spamd_buffer + offset,read - offset,0); if (wrote == -1) { log_write(0, LOG_MAIN|LOG_PANIC, "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno)); (void)close(spamd_sock); goto defer; } if (offset + wrote != read) { offset += wrote; goto again; } } } while (!feof(mbox_file) && !ferror(mbox_file)); if (ferror(mbox_file)) { log_write(0, LOG_MAIN|LOG_PANIC, "%s error reading spool file: %s", loglabel, strerror(errno)); (void)close(spamd_sock); goto defer; } (void)fclose(mbox_file); /* we're done sending, close socket for writing */ shutdown(spamd_sock,SHUT_WR); /* read spamd response using what's left of the timeout. */ memset(spamd_buffer, 0, sizeof(spamd_buffer)); offset = 0; while ((i = ip_recv(spamd_sock, spamd_buffer + offset, sizeof(spamd_buffer) - offset - 1, sd->timeout - time(NULL) + start)) > 0) offset += i; spamd_buffer[offset] = '\0'; /* guard byte */ /* error handling */ if (i <= 0 && errno != 0) { log_write(0, LOG_MAIN|LOG_PANIC, "%s error reading from spamd %s, socket: %s", loglabel, callout_address, strerror(errno)); (void)close(spamd_sock); return DEFER; } /* reading done */ (void)close(spamd_sock); if (sd->is_rspamd) { /* rspamd variant of reply */ int r; if ( (r = sscanf(CS spamd_buffer, "RSPAMD/%7s 0 EX_OK\r\nMetric: default; %7s %lf / %lf / %lf\r\n%n", spamd_version, spamd_short_result, &spamd_score, &spamd_threshold, &spamd_reject_score, &spamd_report_offset)) != 5 || spamd_report_offset >= offset /* verify within buffer */ ) { log_write(0, LOG_MAIN|LOG_PANIC, "%s cannot parse spamd %s, output: %d", loglabel, callout_address, r); return DEFER; } /* now parse action */ p = &spamd_buffer[spamd_report_offset]; if (Ustrncmp(p, "Action: ", sizeof("Action: ") - 1) == 0) { p += sizeof("Action: ") - 1; q = &spam_action_buffer[0]; while (*p && *p != '\r' && (q - spam_action_buffer) < sizeof(spam_action_buffer) - 1) *q++ = *p++; *q = '\0'; } } else { /* spamassassin */ /* dig in the spamd output and put the report in a multiline header, if requested */ if (sscanf(CS spamd_buffer, "SPAMD/%7s 0 EX_OK\r\nContent-length: %*u\r\n\r\n%lf/%lf\r\n%n", spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3) { /* try to fall back to pre-2.50 spamd output */ if (sscanf(CS spamd_buffer, "SPAMD/%7s 0 EX_OK\r\nSpam: %*s ; %lf / %lf\r\n\r\n%n", spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3) { log_write(0, LOG_MAIN|LOG_PANIC, "%s cannot parse spamd %s output", loglabel, callout_address); return DEFER; } } Ustrcpy(spam_action_buffer, spamd_score >= spamd_threshold ? "reject" : "no action"); } /* Create report. Since this is a multiline string, we must hack it into shape first */ p = &spamd_buffer[spamd_report_offset]; q = spam_report_buffer; while (*p != '\0') { /* skip \r */ if (*p == '\r') { p++; continue; } *q++ = *p; if (*p++ == '\n') { /* add an extra space after the newline to ensure that it is treated as a header continuation line */ *q++ = ' '; } } /* NULL-terminate */ *q-- = '\0'; /* cut off trailing leftovers */ while (*q <= ' ') *q-- = '\0'; spam_report = spam_report_buffer; spam_action = spam_action_buffer; /* create spam bar */ spamd_score_char = spamd_score > 0 ? '+' : '-'; j = abs((int)(spamd_score)); i = 0; if (j != 0) while ((i < j) && (i <= MAX_SPAM_BAR_CHARS)) spam_bar_buffer[i++] = spamd_score_char; else { spam_bar_buffer[0] = '/'; i = 1; } spam_bar_buffer[i] = '\0'; spam_bar = spam_bar_buffer; /* create "float" spam score */ (void)string_format(spam_score_buffer, sizeof(spam_score_buffer), "%.1f", spamd_score); spam_score = spam_score_buffer; /* create "int" spam score */ j = (int)((spamd_score + 0.001)*10); (void)string_format(spam_score_int_buffer, sizeof(spam_score_int_buffer), "%d", j); spam_score_int = spam_score_int_buffer; /* compare threshold against score */ spam_rc = spamd_score >= spamd_threshold ? OK /* spam as determined by user's threshold */ : FAIL; /* not spam */ /* remember expanded spamd_address if needed */ if (spamd_address_work != spamd_address) prev_spamd_address_work = string_copy(spamd_address_work); /* remember user name and "been here" for it */ Ustrcpy(prev_user_name, user_name); spam_ok = 1; return override ? OK /* always return OK, no matter what the score */ : spam_rc; defer: (void)fclose(mbox_file); return DEFER; }
int lf_sqlperform(const uschar *name, const uschar *optionname, const uschar *optserverlist, const uschar *query, uschar **result, uschar **errmsg, BOOL *do_cache, int(*fn)(const uschar *, uschar *, uschar **, uschar **, BOOL *, BOOL *)) { int sep, rc; uschar *server; const uschar *serverlist; uschar buffer[512]; BOOL defer_break = FALSE; DEBUG(D_lookup) debug_printf("%s query: %s\n", name, query); /* Handle queries that do not have server information at the start. */ if (Ustrncmp(query, "servers", 7) != 0) { sep = 0; serverlist = optserverlist; while ((server = string_nextinlist(&serverlist, &sep, buffer, sizeof(buffer))) != NULL) { rc = (*fn)(query, server, result, errmsg, &defer_break, do_cache); if (rc != DEFER || defer_break) return rc; } if (optserverlist == NULL) *errmsg = string_sprintf("no %s servers defined (%s option)", name, optionname); } /* Handle queries that do have server information at the start. */ else { int qsep; const uschar *s, *ss; const uschar *qserverlist; uschar *qserver; uschar qbuffer[512]; s = query + 7; while (isspace(*s)) s++; if (*s++ != '=') { *errmsg = string_sprintf("missing = after \"servers\" in %s lookup", name); return DEFER; } while (isspace(*s)) s++; ss = Ustrchr(s, ';'); if (ss == NULL) { *errmsg = string_sprintf("missing ; after \"servers=\" in %s lookup", name); return DEFER; } if (ss == s) { *errmsg = string_sprintf("\"servers=\" defines no servers in \"%s\"", query); return DEFER; } qserverlist = string_sprintf("%.*s", ss - s, s); qsep = 0; while ((qserver = string_nextinlist(&qserverlist, &qsep, qbuffer, sizeof(qbuffer))) != NULL) { if (Ustrchr(qserver, '/') != NULL) server = qserver; else { int len = Ustrlen(qserver); sep = 0; serverlist = optserverlist; while ((server = string_nextinlist(&serverlist, &sep, buffer, sizeof(buffer))) != NULL) { if (Ustrncmp(server, qserver, len) == 0 && server[len] == '/') break; } if (server == NULL) { *errmsg = string_sprintf("%s server \"%s\" not found in %s", name, qserver, optionname); return DEFER; } } rc = (*fn)(ss+1, server, result, errmsg, &defer_break, do_cache); if (rc != DEFER || defer_break) return rc; } } return DEFER; }
static int control_ldap_search(uschar *ldap_url, int search_type, uschar **res, uschar **errmsg) { BOOL defer_break = FALSE; int timelimit = LDAP_NO_LIMIT; int sizelimit = LDAP_NO_LIMIT; int tcplimit = 0; int sep = 0; int dereference = LDAP_DEREF_NEVER; void* referrals = LDAP_OPT_ON; uschar *url = ldap_url; uschar *p; uschar *user = NULL; uschar *password = NULL; uschar *server, *list; uschar buffer[512]; while (isspace(*url)) url++; /* Until the string begins "ldap", search for the other parameter settings that are recognized. They are of the form NAME=VALUE, with the value being optionally double-quoted. There must still be a space after it, however. No NAME has the value "ldap". */ while (strncmpic(url, US"ldap", 4) != 0) { uschar *name = url; while (*url != 0 && *url != '=') url++; if (*url == '=') { int namelen; uschar *value; namelen = ++url - name; value = string_dequote(&url); if (isspace(*url)) { if (strncmpic(name, US"USER="******"PASS="******"SIZE=", namelen) == 0) sizelimit = Uatoi(value); else if (strncmpic(name, US"TIME=", namelen) == 0) timelimit = Uatoi(value); else if (strncmpic(name, US"CONNECT=", namelen) == 0) tcplimit = Uatoi(value); else if (strncmpic(name, US"NETTIME=", namelen) == 0) tcplimit = Uatoi(value); /* Don't know if all LDAP libraries have LDAP_OPT_DEREF */ #ifdef LDAP_OPT_DEREF else if (strncmpic(name, US"DEREFERENCE=", namelen) == 0) { if (strcmpic(value, US"never") == 0) dereference = LDAP_DEREF_NEVER; else if (strcmpic(value, US"searching") == 0) dereference = LDAP_DEREF_SEARCHING; else if (strcmpic(value, US"finding") == 0) dereference = LDAP_DEREF_FINDING; if (strcmpic(value, US"always") == 0) dereference = LDAP_DEREF_ALWAYS; } #else else if (strncmpic(name, US"DEREFERENCE=", namelen) == 0) { *errmsg = string_sprintf("LDAP_OP_DEREF not defined in this LDAP " "library - cannot use \"dereference\""); DEBUG(D_lookup) debug_printf("%s\n", *errmsg); return DEFER; } #endif #ifdef LDAP_OPT_REFERRALS else if (strncmpic(name, US"REFERRALS=", namelen) == 0) { if (strcmpic(value, US"follow") == 0) referrals = LDAP_OPT_ON; else if (strcmpic(value, US"nofollow") == 0) referrals = LDAP_OPT_OFF; else { *errmsg = string_sprintf("LDAP option REFERRALS is not \"follow\" " "or \"nofollow\""); DEBUG(D_lookup) debug_printf("%s\n", *errmsg); return DEFER; } } #else else if (strncmpic(name, US"REFERRALS=", namelen) == 0) { *errmsg = string_sprintf("LDAP_OP_REFERRALS not defined in this LDAP " "library - cannot use \"referrals\""); DEBUG(D_lookup) debug_printf("%s\n", *errmsg); return DEFER; } #endif else { *errmsg = string_sprintf("unknown parameter \"%.*s\" precedes LDAP URL", namelen, name); DEBUG(D_lookup) debug_printf("LDAP query error: %s\n", *errmsg); return DEFER; } while (isspace(*url)) url++; continue; } } *errmsg = US"malformed parameter setting precedes LDAP URL"; DEBUG(D_lookup) debug_printf("LDAP query error: %s\n", *errmsg); return DEFER; } /* If user is set, de-URL-quote it. Some LDAP libraries do this for themselves, but it seems that not all behave like this. The DN for the user is often the result of ${quote_ldap_dn:...} quoting, which does apply URL quoting, because that is needed when the DN is used as a base DN in a query. Sigh. This is all far too complicated. */ if (user != NULL) { uschar *s; uschar *t = user; for (s = user; *s != 0; s++) { int c, d; if (*s == '%' && isxdigit(c=s[1]) && isxdigit(d=s[2])) { c = tolower(c); d = tolower(d); *t++ = (((c >= 'a')? (10 + c - 'a') : c - '0') << 4) | ((d >= 'a')? (10 + d - 'a') : d - '0'); s += 2; } else *t++ = *s; } *t = 0; } DEBUG(D_lookup) debug_printf("LDAP parameters: user=%s pass=%s size=%d time=%d connect=%d " "dereference=%d referrals=%s\n", user, password, sizelimit, timelimit, tcplimit, dereference, (referrals == LDAP_OPT_ON)? "on" : "off"); /* If the request is just to check authentication, some credentials must be given. The password must not be empty because LDAP binds with an empty password are considered anonymous, and will succeed on most installations. */ if (search_type == SEARCH_LDAP_AUTH) { if (user == NULL || password == NULL) { *errmsg = US"ldapauth lookups must specify the username and password"; return DEFER; } if (password[0] == 0) { DEBUG(D_lookup) debug_printf("Empty password: ldapauth returns FAIL\n"); return FAIL; } } /* Check for valid ldap url starters */ p = url + 4; if (tolower(*p) == 's' || tolower(*p) == 'i') p++; if (Ustrncmp(p, "://", 3) != 0) { *errmsg = string_sprintf("LDAP URL does not start with \"ldap://\", " "\"ldaps://\", or \"ldapi://\" (it starts with \"%.16s...\")", url); DEBUG(D_lookup) debug_printf("LDAP query error: %s\n", *errmsg); return DEFER; } /* No default servers, or URL contains a server name: just one attempt */ if (eldap_default_servers == NULL || p[3] != '/') { return perform_ldap_search(url, NULL, 0, search_type, res, errmsg, &defer_break, user, password, sizelimit, timelimit, tcplimit, dereference, referrals); } /* Loop through the default servers until OK or FAIL */ list = eldap_default_servers; while ((server = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL) { int rc; int port = 0; uschar *colon = Ustrchr(server, ':'); if (colon != NULL) { *colon = 0; port = Uatoi(colon+1); } rc = perform_ldap_search(url, server, port, search_type, res, errmsg, &defer_break, user, password, sizelimit, timelimit, tcplimit, dereference, referrals); if (rc != DEFER || defer_break) return rc; } return DEFER; }
static BOOL set_up_direct_command(const uschar ***argvptr, uschar *cmd, BOOL expand_arguments, int expand_fail, address_item *addr, uschar *tname, pipe_transport_options_block *ob) { BOOL permitted = FALSE; const uschar **argv; uschar buffer[64]; /* Set up "transport <name>" to be put in any error messages, and then call the common function for creating an argument list and expanding the items if necessary. If it fails, this function fails (error information is in the addresses). */ sprintf(CS buffer, "%.50s transport", tname); if (!transport_set_up_command(argvptr, cmd, expand_arguments, expand_fail, addr, buffer, NULL)) return FALSE; /* Point to the set-up arguments. */ argv = *argvptr; /* If allow_commands is set, see if the command is in the permitted list. */ if (ob->allow_commands != NULL) { int sep = 0; const uschar *s; uschar *p; uschar buffer[256]; if (!(s = expand_string(ob->allow_commands))) { addr->transport_return = DEFER; addr->message = string_sprintf("failed to expand string \"%s\" " "for %s transport: %s", ob->allow_commands, tname, expand_string_message); return FALSE; } while ((p = string_nextinlist(&s, &sep, buffer, sizeof(buffer)))) if (Ustrcmp(p, argv[0]) == 0) { permitted = TRUE; break; } } /* If permitted is TRUE it means the command was found in the allowed list, and no further checks are done. If permitted = FALSE, it either means allow_commands wasn't set, or that the command didn't match anything in the list. In both cases, if restrict_to_path is set, we fail if the command contains any slashes, but if restrict_to_path is not set, we must fail the command only if allow_commands is set. */ if (!permitted) { if (ob->restrict_to_path) { if (Ustrchr(argv[0], '/') != NULL) { addr->transport_return = FAIL; addr->message = string_sprintf("\"/\" found in \"%s\" (command for %s " "transport) - failed for security reasons", cmd, tname); return FALSE; } } else if (ob->allow_commands != NULL) { addr->transport_return = FAIL; addr->message = string_sprintf("\"%s\" command not permitted by %s " "transport", argv[0], tname); return FALSE; } } /* If the command is not an absolute path, search the PATH directories for it. */ if (argv[0][0] != '/') { int sep = 0; uschar *p; const uschar *listptr = ob->path; uschar buffer[1024]; while ((p = string_nextinlist(&listptr, &sep, buffer, sizeof(buffer))) != NULL) { struct stat statbuf; sprintf(CS big_buffer, "%.256s/%.256s", p, argv[0]); if (Ustat(big_buffer, &statbuf) == 0) { argv[0] = string_copy(big_buffer); break; } } if (p == NULL) { addr->transport_return = FAIL; addr->message = string_sprintf("\"%s\" command not found for %s transport", argv[0], tname); return FALSE; } } return TRUE; }
int dnslookup_router_entry( router_instance *rblock, /* data for this instantiation */ address_item *addr, /* address we are working on */ struct passwd *pw, /* passwd entry after check_local_user */ int verify, /* v_none/v_recipient/v_sender/v_expn */ address_item **addr_local, /* add it to this if it's local */ address_item **addr_remote, /* add it to this if it's remote */ address_item **addr_new, /* put new addresses on here */ address_item **addr_succeed) /* put old address here on success */ { host_item h; int rc; int widen_sep = 0; int whichrrs = HOST_FIND_BY_MX | HOST_FIND_BY_A; dnslookup_router_options_block *ob = (dnslookup_router_options_block *)(rblock->options_block); uschar *srv_service = NULL; uschar *widen = NULL; uschar *pre_widen = addr->domain; uschar *post_widen = NULL; uschar *fully_qualified_name; uschar *listptr; uschar widen_buffer[256]; addr_new = addr_new; /* Keep picky compilers happy */ addr_succeed = addr_succeed; DEBUG(D_route) debug_printf("%s router called for %s\n domain = %s\n", rblock->name, addr->address, addr->domain); /* If an SRV check is required, expand the service name */ if (ob->check_srv != NULL) { srv_service = expand_string(ob->check_srv); if (srv_service == NULL && !expand_string_forcedfail) { addr->message = string_sprintf("%s router: failed to expand \"%s\": %s", rblock->name, ob->check_srv, expand_string_message); return DEFER; } else whichrrs |= HOST_FIND_BY_SRV; } /* Set up the first of any widening domains. The code further down copes with either pre- or post-widening, but at present there is no way to turn on pre-widening, as actually doing so seems like a rather bad idea, and nobody has requested it. Pre-widening would cause local abbreviated names to take precedence over global names. For example, if the domain is "xxx.ch" it might be something in the "ch" toplevel domain, but it also might be xxx.ch.xyz.com. The choice of pre- or post-widening affects which takes precedence. If ever somebody comes up with some kind of requirement for pre-widening, presumably with some conditions under which it is done, it can be selected here. The rewrite_headers option works only when routing an address at transport time, because the alterations to the headers are not persistent so must be worked out immediately before they are used. Sender addresses are routed for verification purposes, but never at transport time, so any header changes that you might expect as a result of sender domain widening do not occur. Therefore we do not perform widening when verifying sender addresses; however, widening sender addresses is OK if we do not have to rewrite the headers. A corollary of this is that if the current address is not the original address, then it does not appear in the message header so it is also OK to widen. The suppression of widening for sender addresses is silent because it is the normal desirable behaviour. */ if (ob->widen_domains != NULL && (verify != v_sender || !ob->rewrite_headers || addr->parent != NULL)) { listptr = ob->widen_domains; widen = string_nextinlist(&listptr, &widen_sep, widen_buffer, sizeof(widen_buffer)); /**** if (some condition requiring pre-widening) { post_widen = pre_widen; pre_widen = NULL; } ****/ } /* Loop to cope with explicit widening of domains as configured. This code copes with widening that may happen before or after the original name. The decision as to which is taken above. */ for (;;) { int flags = whichrrs; BOOL removed = FALSE; if (pre_widen != NULL) { h.name = pre_widen; pre_widen = NULL; } else if (widen != NULL) { h.name = string_sprintf("%s.%s", addr->domain, widen); widen = string_nextinlist(&listptr, &widen_sep, widen_buffer, sizeof(widen_buffer)); DEBUG(D_route) debug_printf("%s router widened %s to %s\n", rblock->name, addr->domain, h.name); } else if (post_widen != NULL) { h.name = post_widen; post_widen = NULL; DEBUG(D_route) debug_printf("%s router trying %s after widening failed\n", rblock->name, h.name); } else return DECLINE; /* Set up the rest of the initial host item. Others may get chained on if there is more than one IP address. We set it up here instead of outside the loop so as to re-initialize if a previous try succeeded but was rejected because of not having an MX record. */ h.next = NULL; h.address = NULL; h.port = PORT_NONE; h.mx = MX_NONE; h.status = hstatus_unknown; h.why = hwhy_unknown; h.last_try = 0; /* Unfortunately, we cannot set the mx_only option in advance, because the DNS lookup may extend an unqualified name. Therefore, we must do the test subsequently. We use the same logic as that for widen_domains above to avoid requesting a header rewrite that cannot work. */ if (verify != v_sender || !ob->rewrite_headers || addr->parent != NULL) { if (ob->qualify_single) flags |= HOST_FIND_QUALIFY_SINGLE; if (ob->search_parents) flags |= HOST_FIND_SEARCH_PARENTS; } rc = host_find_bydns(&h, rblock->ignore_target_hosts, flags, srv_service, ob->srv_fail_domains, ob->mx_fail_domains, &fully_qualified_name, &removed); if (removed) setflag(addr, af_local_host_removed); /* If host found with only address records, test for the domain's being in the mx_domains list. Note that this applies also to SRV records; the name of the option is historical. */ if ((rc == HOST_FOUND || rc == HOST_FOUND_LOCAL) && h.mx < 0 && ob->mx_domains != NULL) { switch(match_isinlist(fully_qualified_name, &(ob->mx_domains), 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) { case DEFER: addr->message = US"lookup defer for mx_domains"; return DEFER; case OK: DEBUG(D_route) debug_printf("%s router rejected %s: no MX record(s)\n", rblock->name, fully_qualified_name); continue; } } /* Deferral returns forthwith, and anything other than failure breaks the loop. */ if (rc == HOST_FIND_AGAIN) { if (rblock->pass_on_timeout) { DEBUG(D_route) debug_printf("%s router timed out, and pass_on_timeout is set\n", rblock->name); return PASS; } addr->message = US"host lookup did not complete"; return DEFER; } if (rc != HOST_FIND_FAILED) break; /* Check to see if the failure is the result of MX records pointing to non-existent domains, and if so, set an appropriate error message; the case of an MX or SRV record pointing to "." is another special case that we can detect. Otherwise "unknown mail domain" is used, which is confusing. Also, in this case don't do the widening. We need check only the first host to see if its MX has been filled in, but there is no address, because if there were any usable addresses returned, we would not have had HOST_FIND_FAILED. As a common cause of this problem is MX records with IP addresses on the RHS, give a special message in this case. */ if (h.mx >= 0 && h.address == NULL) { setflag(addr, af_pass_message); /* This is not a security risk */ if (h.name[0] == 0) addr->message = US"an MX or SRV record indicated no SMTP service"; else { addr->message = US"all relevant MX records point to non-existent hosts"; if (!allow_mx_to_ip && string_is_ip_address(h.name, NULL) != 0) { addr->user_message = string_sprintf("It appears that the DNS operator for %s\n" "has installed an invalid MX record with an IP address\n" "instead of a domain name on the right hand side.", addr->domain); addr->message = string_sprintf("%s or (invalidly) to IP addresses", addr->message); } } return DECLINE; } /* If there's a syntax error, do not continue with any widening, and note the error. */ if (host_find_failed_syntax) { addr->message = string_sprintf("mail domain \"%s\" is syntactically " "invalid", h.name); return DECLINE; } } /* If the original domain name has been changed as a result of the host lookup, set up a child address for rerouting and request header rewrites if so configured. Then yield REROUTED. However, if the only change is a change of case in the domain name, which some resolvers yield (others don't), just change the domain name in the original address so that the official version is used in RCPT commands. */ if (Ustrcmp(addr->domain, fully_qualified_name) != 0) { if (strcmpic(addr->domain, fully_qualified_name) == 0) { uschar *at = Ustrrchr(addr->address, '@'); memcpy(at+1, fully_qualified_name, Ustrlen(at+1)); } else { rf_change_domain(addr, fully_qualified_name, ob->rewrite_headers, addr_new); return REROUTED; } } /* If the yield is HOST_FOUND_LOCAL, the remote domain name either found MX records with the lowest numbered one pointing to a host with an IP address that is set on one of the interfaces of this machine, or found A records or got addresses from gethostbyname() that contain one for this machine. This can happen quite legitimately if the original name was a shortened form of a domain, but we will have picked that up already via the name change test above. Otherwise, the action to be taken can be configured by the self option, the handling of which is in a separate function, as it is also required for other routers. */ if (rc == HOST_FOUND_LOCAL) { rc = rf_self_action(addr, &h, rblock->self_code, rblock->self_rewrite, rblock->self, addr_new); if (rc != OK) return rc; } /* Otherwise, insist on being a secondary MX if so configured */ else if (ob->check_secondary_mx && !testflag(addr, af_local_host_removed)) { DEBUG(D_route) debug_printf("check_secondary_mx set and local host not secondary\n"); return DECLINE; } /* Set up the errors address, if any. */ rc = rf_get_errors_address(addr, rblock, verify, &(addr->p.errors_address)); if (rc != OK) return rc; /* Set up the additional and removeable headers for this address. */ rc = rf_get_munge_headers(addr, rblock, &(addr->p.extra_headers), &(addr->p.remove_headers)); if (rc != OK) return rc; /* Get store in which to preserve the original host item, chained on to the address. */ addr->host_list = store_get(sizeof(host_item)); addr->host_list[0] = h; /* Fill in the transport and queue the address for delivery. */ if (!rf_get_transport(rblock->transport_name, &(rblock->transport), addr, rblock->name, NULL)) return DEFER; addr->transport = rblock->transport; return rf_queue_add(addr, addr_local, addr_remote, rblock, pw)? OK : DEFER; }
int dcc_process(uschar **listptr) { int sep = 0; uschar *list = *listptr; FILE *data_file; uschar *dcc_daemon_ip = US""; uschar *dcc_default_ip_option = US"127.0.0.1"; uschar *dcc_ip_option = US""; uschar *dcc_helo_option = US"localhost"; uschar *dcc_reject_message = US"Rejected by DCC"; uschar *xtra_hdrs = NULL; /* from local_scan */ int i, j, k, c, retval, sockfd, resp, line; unsigned int portnr; struct sockaddr_un serv_addr; struct sockaddr_in serv_addr_in; struct hostent *ipaddress; uschar sockpath[128]; uschar sockip[40], client_ip[40]; uschar opts[128]; uschar rcpt[128], from[128]; uschar sendbuf[4096]; uschar recvbuf[4096]; uschar dcc_return_text[1024]; uschar mbox_path[1024]; uschar message_subdir[2]; struct header_line *dcchdr; uschar *dcc_acl_options; uschar dcc_acl_options_buffer[10]; uschar dcc_xtra_hdrs[1024]; /* grep 1st option */ if ((dcc_acl_options = string_nextinlist(&list, &sep, dcc_acl_options_buffer, sizeof(dcc_acl_options_buffer))) != NULL) { /* parse 1st option */ if ( (strcmpic(dcc_acl_options,US"false") == 0) || (Ustrcmp(dcc_acl_options,"0") == 0) ) { /* explicitly no matching */ return FAIL; }; /* special cases (match anything except empty) */ if ( (strcmpic(dcc_acl_options,US"true") == 0) || (Ustrcmp(dcc_acl_options,"*") == 0) || (Ustrcmp(dcc_acl_options,"1") == 0) ) { dcc_acl_options = dcc_acl_options; }; } else { /* empty means "don't match anything" */ return FAIL; }; sep = 0; /* if we scanned this message last time, just return */ if ( dcc_ok ) return dcc_rc; /* open the spooled body */ message_subdir[1] = '\0'; for (i = 0; i < 2; i++) { message_subdir[0] = (split_spool_directory == (i == 0))? message_id[5] : 0; sprintf(CS mbox_path, "%s/input/%s/%s-D", spool_directory, message_subdir, message_id); data_file = Ufopen(mbox_path,"rb"); if (data_file != NULL) break; }; if (data_file == NULL) { /* error while spooling */ log_write(0, LOG_MAIN|LOG_PANIC, "dcc acl condition: error while opening spool file"); return DEFER; }; /* Initialize the variables */ bzero(sockip,sizeof(sockip)); if (dccifd_address) { if (dccifd_address[0] == '/') Ustrncpy(sockpath, dccifd_address, sizeof(sockpath)); else if( sscanf(CS dccifd_address, "%s %u", sockip, &portnr) != 2) { log_write(0, LOG_MAIN, "dcc acl condition: warning - invalid dccifd address: '%s'", dccifd_address); (void)fclose(data_file); return DEFER; } } /* opts is what we send as dccifd options - see man dccifd */ /* We don't support any other option than 'header' so just copy that */ bzero(opts,sizeof(opts)); Ustrncpy(opts, "header", sizeof(opts)-1); Ustrncpy(client_ip, dcc_ip_option, sizeof(client_ip)-1); /* If the dcc_client_ip is not provided use the * sender_host_address or 127.0.0.1 if it is NULL */ DEBUG(D_acl) debug_printf("my_ip_option = %s - client_ip = %s - sender_host_address = %s\n", dcc_ip_option, client_ip, sender_host_address); if(!(Ustrcmp(client_ip, ""))){ /* Do we have a sender_host_address or is it NULL? */ if(sender_host_address){ Ustrncpy(client_ip, sender_host_address, sizeof(client_ip)-1); } else { /* sender_host_address is NULL which means it comes from localhost */ Ustrncpy(client_ip, dcc_default_ip_option, sizeof(client_ip)-1); } } DEBUG(D_acl) debug_printf("Client IP: %s\n", client_ip); Ustrncpy(sockip, dcc_daemon_ip, sizeof(sockip)-1); /* strncat(opts, my_request, strlen(my_request)); */ Ustrcat(opts, "\n"); Ustrncat(opts, client_ip, sizeof(opts)-Ustrlen(opts)-1); Ustrncat(opts, "\nHELO ", sizeof(opts)-Ustrlen(opts)-1); Ustrncat(opts, dcc_helo_option, sizeof(opts)-Ustrlen(opts)-2); Ustrcat(opts, "\n"); /* initialize the other variables */ dcchdr = header_list; /* we set the default return value to DEFER */ retval = DEFER; bzero(sendbuf,sizeof(sendbuf)); bzero(dcc_header_str,sizeof(dcc_header_str)); bzero(rcpt,sizeof(rcpt)); bzero(from,sizeof(from)); /* send a null return path as "<>". */ if (Ustrlen(sender_address) > 0) Ustrncpy(from, sender_address, sizeof(from)); else Ustrncpy(from, "<>", sizeof(from)); Ustrncat(from, "\n", sizeof(from)-Ustrlen(from)-1); /************************************** * Now creating the socket connection * **************************************/ /* If there is a dcc_daemon_ip, we use a tcp socket, otherwise a UNIX socket */ if(Ustrcmp(sockip, "")){ ipaddress = gethostbyname((char *)sockip); bzero((char *) &serv_addr_in, sizeof(serv_addr_in)); serv_addr_in.sin_family = AF_INET; bcopy((char *)ipaddress->h_addr, (char *)&serv_addr_in.sin_addr.s_addr, ipaddress->h_length); serv_addr_in.sin_port = htons(portnr); if ((sockfd = socket(AF_INET, SOCK_STREAM,0)) < 0){ DEBUG(D_acl) debug_printf("Creating socket failed: %s\n", strerror(errno)); log_write(0,LOG_REJECT,"Creating socket failed: %s\n", strerror(errno)); /* if we cannot create the socket, defer the mail */ (void)fclose(data_file); return retval; } /* Now connecting the socket (INET) */ if (connect(sockfd, (struct sockaddr *)&serv_addr_in, sizeof(serv_addr_in)) < 0){ DEBUG(D_acl) debug_printf("Connecting socket failed: %s\n", strerror(errno)); log_write(0,LOG_REJECT,"Connecting socket failed: %s\n", strerror(errno)); /* if we cannot contact the socket, defer the mail */ (void)fclose(data_file); return retval; } } else { /* connecting to the dccifd UNIX socket */ bzero((char *)&serv_addr,sizeof(serv_addr)); serv_addr.sun_family = AF_UNIX; Ustrcpy(serv_addr.sun_path, sockpath); if ((sockfd = socket(AF_UNIX, SOCK_STREAM,0)) < 0){ DEBUG(D_acl) debug_printf("Creating socket failed: %s\n", strerror(errno)); log_write(0,LOG_REJECT,"Creating socket failed: %s\n", strerror(errno)); /* if we cannot create the socket, defer the mail */ (void)fclose(data_file); return retval; } /* Now connecting the socket (UNIX) */ if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){ DEBUG(D_acl) debug_printf("Connecting socket failed: %s\n", strerror(errno)); log_write(0,LOG_REJECT,"Connecting socket failed: %s\n", strerror(errno)); /* if we cannot contact the socket, defer the mail */ (void)fclose(data_file); return retval; } } /* the socket is open, now send the options to dccifd*/ DEBUG(D_acl) debug_printf("\n---------------------------\nSocket opened; now sending input\n-----------------\n"); /* First, fill in the input buffer */ Ustrncpy(sendbuf, opts, sizeof(sendbuf)); Ustrncat(sendbuf, from, sizeof(sendbuf)-Ustrlen(sendbuf)-1); DEBUG(D_acl) { debug_printf("opts = %s\nsender = %s\nrcpt count = %d\n", opts, from, recipients_count); debug_printf("Sending options:\n****************************\n"); } /* let's send each of the recipients to dccifd */ for (i = 0; i < recipients_count; i++){ DEBUG(D_acl) debug_printf("recipient = %s\n",recipients_list[i].address); if(Ustrlen(sendbuf) + Ustrlen(recipients_list[i].address) > sizeof(sendbuf)) { DEBUG(D_acl) debug_printf("Writing buffer: %s\n", sendbuf); flushbuffer(sockfd, sendbuf); bzero(sendbuf, sizeof(sendbuf)); } Ustrncat(sendbuf, recipients_list[i].address, sizeof(sendbuf)-Ustrlen(sendbuf)-1); Ustrncat(sendbuf, "\r\n", sizeof(sendbuf)-Ustrlen(sendbuf)-1); } /* send a blank line between options and message */ Ustrncat(sendbuf, "\n", sizeof(sendbuf)-Ustrlen(sendbuf)-1); /* Now we send the input buffer */ DEBUG(D_acl) debug_printf("%s\n****************************\n", sendbuf); flushbuffer(sockfd, sendbuf); /* now send the message */ /* Clear the input buffer */ bzero(sendbuf, sizeof(sendbuf)); /* First send the headers */ /* Now send the headers */ DEBUG(D_acl) debug_printf("Sending headers:\n****************************\n"); Ustrncpy(sendbuf, dcchdr->text, sizeof(sendbuf)-2); while((dcchdr=dcchdr->next)) { if(dcchdr->slen > sizeof(sendbuf)-2) { /* The size of the header is bigger than the size of * the input buffer, so split it up in smaller parts. */ flushbuffer(sockfd, sendbuf); bzero(sendbuf, sizeof(sendbuf)); j = 0; while(j < dcchdr->slen) { for(i = 0; i < sizeof(sendbuf)-2; i++) { sendbuf[i] = dcchdr->text[j]; j++; } flushbuffer(sockfd, sendbuf); bzero(sendbuf, sizeof(sendbuf)); } } else if(Ustrlen(sendbuf) + dcchdr->slen > sizeof(sendbuf)-2) { flushbuffer(sockfd, sendbuf); bzero(sendbuf, sizeof(sendbuf)); Ustrncpy(sendbuf, dcchdr->text, sizeof(sendbuf)-2); } else { Ustrncat(sendbuf, dcchdr->text, sizeof(sendbuf)-Ustrlen(sendbuf)-2); } } /* a blank line seperates header from body */ Ustrncat(sendbuf, "\n", sizeof(sendbuf)-Ustrlen(sendbuf)-1); flushbuffer(sockfd, sendbuf); DEBUG(D_acl) debug_printf("\n****************************\n%s", sendbuf); /* Clear the input buffer */ bzero(sendbuf, sizeof(sendbuf)); /* now send the body */ DEBUG(D_acl) debug_printf("Writing body:\n****************************\n"); (void)fseek(data_file, SPOOL_DATA_START_OFFSET, SEEK_SET); while((fread(sendbuf, 1, sizeof(sendbuf)-1, data_file)) > 0) { flushbuffer(sockfd, sendbuf); bzero(sendbuf, sizeof(sendbuf)); } DEBUG(D_acl) debug_printf("\n****************************\n"); /* shutdown() the socket */ if(shutdown(sockfd, 1) < 0){ DEBUG(D_acl) debug_printf("Couldn't shutdown socket: %s\n", strerror(errno)); log_write(0,LOG_MAIN,"Couldn't shutdown socket: %s\n", strerror(errno)); /* If there is a problem with the shutdown() * defer the mail. */ (void)fclose(data_file); return retval; } DEBUG(D_acl) debug_printf("\n-------------------------\nInput sent.\n-------------------------\n"); /******************************** * receiving output from dccifd * ********************************/ DEBUG(D_acl) debug_printf("\n-------------------------------------\nNow receiving output from server\n-----------------------------------\n"); /****************************************************************** * We should get 3 lines: * * 1/ First line is overall result: either 'A' for Accept, * * 'R' for Reject, 'S' for accept Some recipients or * * 'T' for a Temporary error. * * 2/ Second line contains the list of Accepted/Rejected * * recipients in the form AARRA (A = accepted, R = rejected). * * 3/ Third line contains the X-DCC header. * ******************************************************************/ line = 1; /* we start at the first line of the output */ j = 0; /* will be used as index for the recipients list */ k = 0; /* initializing the index of the X-DCC header: dcc_header_str[k] */ /* Let's read from the socket until there's nothing left to read */ bzero(recvbuf, sizeof(recvbuf)); while((resp = read(sockfd, recvbuf, sizeof(recvbuf)-1)) > 0) { /* How much did we get from the socket */ c = Ustrlen(recvbuf) + 1; DEBUG(D_acl) debug_printf("Length of the output buffer is: %d\nOutput buffer is:\n------------\n%s\n-----------\n", c, recvbuf); /* Now let's read each character and see what we've got */ for(i = 0; i < c; i++) { /* First check if we reached the end of the line and * then increment the line counter */ if(recvbuf[i] == '\n') { line++; } else { /* The first character of the first line is the * overall response. If there's another character * on that line it is not correct. */ if(line == 1) { if(i == 0) { /* Now get the value and set the * return value accordingly */ if(recvbuf[i] == 'A') { DEBUG(D_acl) debug_printf("Overall result = A\treturning OK\n"); Ustrcpy(dcc_return_text, "Mail accepted by DCC"); dcc_result = US"A"; retval = OK; } else if(recvbuf[i] == 'R') { DEBUG(D_acl) debug_printf("Overall result = R\treturning FAIL\n"); dcc_result = US"R"; retval = FAIL; if(sender_host_name) { log_write(0, LOG_MAIN, "H=%s [%s] F=<%s>: rejected by DCC", sender_host_name, sender_host_address, sender_address); } else { log_write(0, LOG_MAIN, "H=[%s] F=<%s>: rejected by DCC", sender_host_address, sender_address); } Ustrncpy(dcc_return_text, dcc_reject_message, Ustrlen(dcc_reject_message) + 1); } else if(recvbuf[i] == 'S') { DEBUG(D_acl) debug_printf("Overall result = S\treturning OK\n"); Ustrcpy(dcc_return_text, "Not all recipients accepted by DCC"); /* Since we're in an ACL we want a global result * so we accept for all */ dcc_result = US"A"; retval = OK; } else if(recvbuf[i] == 'G') { DEBUG(D_acl) debug_printf("Overall result = G\treturning FAIL\n"); Ustrcpy(dcc_return_text, "Greylisted by DCC"); dcc_result = US"G"; retval = FAIL; } else if(recvbuf[i] == 'T') { DEBUG(D_acl) debug_printf("Overall result = T\treturning DEFER\n"); retval = DEFER; log_write(0,LOG_MAIN,"Temporary error with DCC: %s\n", recvbuf); Ustrcpy(dcc_return_text, "Temporary error with DCC"); dcc_result = US"T"; } else { DEBUG(D_acl) debug_printf("Overall result = something else\treturning DEFER\n"); retval = DEFER; log_write(0,LOG_MAIN,"Unknown DCC response: %s\n", recvbuf); Ustrcpy(dcc_return_text, "Unknown DCC response"); dcc_result = US"T"; } } else { /* We're on the first line but not on the first character, * there must be something wrong. */ DEBUG(D_acl) debug_printf("Line = %d but i = %d != 0 character is %c - This is wrong!\n", line, i, recvbuf[i]); log_write(0,LOG_MAIN,"Wrong header from DCC, output is %s\n", recvbuf); } } else if(line == 2) { /* On the second line we get a list of * answers for each recipient. We don't care about * it because we're in an acl and take the * global result. */ } else if(line > 2) { /* The third and following lines are the X-DCC header, * so we store it in dcc_header_str. */ /* check if we don't get more than we can handle */ if(k < sizeof(dcc_header_str)) { dcc_header_str[k] = recvbuf[i]; k++; } else { DEBUG(D_acl) debug_printf("We got more output than we can store in the X-DCC header. Truncating at 120 characters.\n"); } } else { /* Wrong line number. There must be a problem with the output. */ DEBUG(D_acl) debug_printf("Wrong line number in output. Line number is %d\n", line); } } } /* we reinitialize the output buffer before we read again */ bzero(recvbuf,sizeof(recvbuf)); } /* We have read everything from the socket */ /* We need to terminate the X-DCC header with a '\n' character. This needs to be k-1 * since dcc_header_str[k] contains '\0'. */ dcc_header_str[k-1] = '\n'; /* Now let's sum up what we've got. */ DEBUG(D_acl) debug_printf("\n--------------------------\nOverall result = %d\nX-DCC header: %sReturn message: %s\ndcc_result: %s\n", retval, dcc_header_str, dcc_return_text, dcc_result); /* We only add the X-DCC header if it starts with X-DCC */ if(!(Ustrncmp(dcc_header_str, "X-DCC", 5))){ dcc_header = dcc_header_str; if(dcc_direct_add_header) { header_add(' ' , "%s", dcc_header_str); /* since the MIME ACL already writes the .eml file to disk without DCC Header we've to erase it */ unspool_mbox(); } } else { DEBUG(D_acl) debug_printf("Wrong format of the X-DCC header: %s\n", dcc_header_str); } /* check if we should add additional headers passed in acl_m_dcc_add_header */ if(dcc_direct_add_header) { if (((xtra_hdrs = expand_string(US"$acl_m_dcc_add_header")) != NULL) && (xtra_hdrs[0] != '\0')) { Ustrncpy(dcc_xtra_hdrs, xtra_hdrs, sizeof(dcc_xtra_hdrs) - 2); if (dcc_xtra_hdrs[Ustrlen(dcc_xtra_hdrs)-1] != '\n') Ustrcat(dcc_xtra_hdrs, "\n"); header_add(' ', "%s", dcc_xtra_hdrs); DEBUG(D_acl) debug_printf("adding additional headers in $acl_m_dcc_add_header: %s", dcc_xtra_hdrs); } } dcc_ok = 1; /* Now return to exim main process */ DEBUG(D_acl) debug_printf("Before returning to exim main process:\nreturn_text = %s - retval = %d\ndcc_result = %s\n", dcc_return_text, retval, dcc_result); (void)fclose(data_file); dcc_rc = retval; return dcc_rc; }
int regex(uschar **listptr) { int sep = 0; uschar *list = *listptr; uschar *regex_string; uschar regex_string_buffer[1024]; unsigned long mbox_size; FILE *mbox_file; pcre *re; pcre_list *re_list_head = NULL; pcre_list *re_list_item; const char *pcre_error; int pcre_erroffset; uschar *linebuffer; long f_pos = 0; /* reset expansion variable */ regex_match_string = NULL; if (mime_stream == NULL) { /* We are in the DATA ACL */ mbox_file = spool_mbox(&mbox_size, NULL); if (mbox_file == NULL) { /* error while spooling */ log_write(0, LOG_MAIN|LOG_PANIC, "regex acl condition: error while creating mbox spool file"); return DEFER; }; } else { f_pos = ftell(mime_stream); mbox_file = mime_stream; }; /* precompile our regexes */ while ((regex_string = string_nextinlist(&list, &sep, regex_string_buffer, sizeof(regex_string_buffer))) != NULL) { /* parse option */ if ( (strcmpic(regex_string,US"false") == 0) || (Ustrcmp(regex_string,"0") == 0) ) { /* explicitly no matching */ continue; }; /* compile our regular expression */ re = pcre_compile( CS regex_string, 0, &pcre_error, &pcre_erroffset, NULL ); if (re == NULL) { log_write(0, LOG_MAIN, "regex acl condition warning - error in regex '%s': %s at offset %d, skipped.", regex_string, pcre_error, pcre_erroffset); continue; } else { re_list_item = store_get(sizeof(pcre_list)); re_list_item->re = re; re_list_item->pcre_text = string_copy(regex_string); re_list_item->next = re_list_head; re_list_head = re_list_item; }; }; /* no regexes -> nothing to do */ if (re_list_head == NULL) { return FAIL; }; /* match each line against all regexes */ linebuffer = store_get(32767); while (fgets(CS linebuffer, 32767, mbox_file) != NULL) { if ( (mime_stream != NULL) && (mime_current_boundary != NULL) ) { /* check boundary */ if (Ustrncmp(linebuffer,"--",2) == 0) { if (Ustrncmp((linebuffer+2),mime_current_boundary,Ustrlen(mime_current_boundary)) == 0) /* found boundary */ break; }; }; re_list_item = re_list_head; do { /* try matcher on the line */ if (pcre_exec(re_list_item->re, NULL, CS linebuffer, (int)Ustrlen(linebuffer), 0, 0, NULL, 0) >= 0) { Ustrncpy(regex_match_string_buffer, re_list_item->pcre_text, 1023); regex_match_string = regex_match_string_buffer; if (mime_stream == NULL) (void)fclose(mbox_file); else { clearerr(mime_stream); fseek(mime_stream,f_pos,SEEK_SET); }; return OK; }; re_list_item = re_list_item->next; } while (re_list_item != NULL); }; if (mime_stream == NULL) (void)fclose(mbox_file); else { clearerr(mime_stream); fseek(mime_stream,f_pos,SEEK_SET); }; /* no matches ... */ return FAIL; }
int spf_process(uschar **listptr, uschar *spf_envelope_sender, int action) { int sep = 0; uschar *list = *listptr; uschar *spf_result_id; uschar spf_result_id_buffer[128]; int rc = SPF_RESULT_PERMERROR; if (!(spf_server && spf_request)) { /* no global context, assume temp error and skip to evaluation */ rc = SPF_RESULT_PERMERROR; goto SPF_EVALUATE; }; if (SPF_request_set_env_from(spf_request, CS spf_envelope_sender)) { /* Invalid sender address. This should be a real rare occurence */ rc = SPF_RESULT_PERMERROR; goto SPF_EVALUATE; } /* get SPF result */ if (action == SPF_PROCESS_FALLBACK) SPF_request_query_fallback(spf_request, &spf_response, CS spf_guess); else SPF_request_query_mailfrom(spf_request, &spf_response); /* set up expansion items */ spf_header_comment = (uschar *)SPF_response_get_header_comment(spf_response); spf_received = (uschar *)SPF_response_get_received_spf(spf_response); spf_result = (uschar *)SPF_strresult(SPF_response_result(spf_response)); spf_smtp_comment = (uschar *)SPF_response_get_smtp_comment(spf_response); rc = SPF_response_result(spf_response); /* We got a result. Now see if we should return OK or FAIL for it */ SPF_EVALUATE: debug_printf("SPF result is %s (%d)\n", SPF_strresult(rc), rc); if (action == SPF_PROCESS_GUESS && (!strcmp (SPF_strresult(rc), "none"))) return spf_process(listptr, spf_envelope_sender, SPF_PROCESS_FALLBACK); while ((spf_result_id = string_nextinlist(&list, &sep, spf_result_id_buffer, sizeof(spf_result_id_buffer))) != NULL) { int negate = 0; int result = 0; /* Check for negation */ if (spf_result_id[0] == '!') { negate = 1; spf_result_id++; }; /* Check the result identifier */ result = Ustrcmp(spf_result_id, spf_result_id_list[rc].name); if (!negate && result==0) return OK; if (negate && result!=0) return OK; }; /* no match */ return FAIL; }
BOOL pipe_transport_entry( transport_instance *tblock, /* data for this instantiation */ address_item *addr) /* address(es) we are working on */ { pid_t pid, outpid; int fd_in, fd_out, rc; int envcount = 0; int envsep = 0; int expand_fail; pipe_transport_options_block *ob = (pipe_transport_options_block *)(tblock->options_block); int timeout = ob->timeout; BOOL written_ok = FALSE; BOOL expand_arguments; const uschar **argv; uschar *envp[50]; const uschar *envlist = ob->environment; uschar *cmd, *ss; uschar *eol = (ob->use_crlf)? US"\r\n" : US"\n"; DEBUG(D_transport) debug_printf("%s transport entered\n", tblock->name); /* Set up for the good case */ addr->transport_return = OK; addr->basic_errno = 0; /* Pipes are not accepted as general addresses, but they can be generated from .forward files or alias files. In those cases, the pfr flag is set, and the command to be obeyed is pointed to by addr->local_part; it starts with the pipe symbol. In other cases, the command is supplied as one of the pipe transport's options. */ if (testflag(addr, af_pfr) && addr->local_part[0] == '|') { if (ob->force_command) { /* Enables expansion of $address_pipe into seperate arguments */ setflag(addr, af_force_command); cmd = ob->cmd; expand_arguments = TRUE; expand_fail = PANIC; } else { cmd = addr->local_part + 1; while (isspace(*cmd)) cmd++; expand_arguments = testflag(addr, af_expand_pipe); expand_fail = FAIL; } } else { cmd = ob->cmd; expand_arguments = TRUE; expand_fail = PANIC; } /* If no command has been supplied, we are in trouble. * We also check for an empty string since it may be * coming from addr->local_part[0] == '|' */ if (cmd == NULL || *cmd == '\0') { addr->transport_return = DEFER; addr->message = string_sprintf("no command specified for %s transport", tblock->name); return FALSE; } /* When a pipe is set up by a filter file, there may be values for $thisaddress and numerical the variables in existence. These are passed in addr->pipe_expandn for use here. */ if (expand_arguments && addr->pipe_expandn != NULL) { uschar **ss = addr->pipe_expandn; expand_nmax = -1; if (*ss != NULL) filter_thisaddress = *ss++; while (*ss != NULL) { expand_nstring[++expand_nmax] = *ss; expand_nlength[expand_nmax] = Ustrlen(*ss++); } } /* The default way of processing the command is to split it up into arguments here, and run it directly. This offers some security advantages. However, there are installations that want by default to run commands under /bin/sh always, so there is an option to do that. */ if (ob->use_shell) { if (!set_up_shell_command(&argv, cmd, expand_arguments, expand_fail, addr, tblock->name)) return FALSE; } else if (!set_up_direct_command(&argv, cmd, expand_arguments, expand_fail, addr, tblock->name, ob)) return FALSE; expand_nmax = -1; /* Reset */ filter_thisaddress = NULL; /* Set up the environment for the command. */ envp[envcount++] = string_sprintf("LOCAL_PART=%s", deliver_localpart); envp[envcount++] = string_sprintf("LOGNAME=%s", deliver_localpart); envp[envcount++] = string_sprintf("USER=%s", deliver_localpart); envp[envcount++] = string_sprintf("LOCAL_PART_PREFIX=%#s", deliver_localpart_prefix); envp[envcount++] = string_sprintf("LOCAL_PART_SUFFIX=%#s", deliver_localpart_suffix); envp[envcount++] = string_sprintf("DOMAIN=%s", deliver_domain); envp[envcount++] = string_sprintf("HOME=%#s", deliver_home); envp[envcount++] = string_sprintf("MESSAGE_ID=%s", message_id); envp[envcount++] = string_sprintf("PATH=%s", ob->path); envp[envcount++] = string_sprintf("RECIPIENT=%#s%#s%#s@%#s", deliver_localpart_prefix, deliver_localpart, deliver_localpart_suffix, deliver_domain); envp[envcount++] = string_sprintf("QUALIFY_DOMAIN=%s", qualify_domain_sender); envp[envcount++] = string_sprintf("SENDER=%s", sender_address); envp[envcount++] = US"SHELL=/bin/sh"; if (addr->host_list != NULL) envp[envcount++] = string_sprintf("HOST=%s", addr->host_list->name); if (timestamps_utc) envp[envcount++] = US"TZ=UTC"; else if (timezone_string != NULL && timezone_string[0] != 0) envp[envcount++] = string_sprintf("TZ=%s", timezone_string); /* Add any requested items */ if (envlist) { envlist = expand_cstring(envlist); if (envlist == NULL) { addr->transport_return = DEFER; addr->message = string_sprintf("failed to expand string \"%s\" " "for %s transport: %s", ob->environment, tblock->name, expand_string_message); return FALSE; } } while ((ss = string_nextinlist(&envlist, &envsep, big_buffer, big_buffer_size)) != NULL) { if (envcount > sizeof(envp)/sizeof(uschar *) - 2) { addr->transport_return = DEFER; addr->message = string_sprintf("too many environment settings for " "%s transport", tblock->name); return FALSE; } envp[envcount++] = string_copy(ss); } envp[envcount] = NULL; /* If the -N option is set, can't do any more. */ if (dont_deliver) { DEBUG(D_transport) debug_printf("*** delivery by %s transport bypassed by -N option", tblock->name); return FALSE; } /* Handling the output from the pipe is tricky. If a file for catching this output is provided, we could in theory just hand that fd over to the process, but this isn't very safe because it might loop and carry on writing for ever (which is exactly what happened in early versions of Exim). Therefore we use the standard child_open() function, which creates pipes. We can then read our end of the output pipe and count the number of bytes that come through, chopping the sub-process if it exceeds some limit. However, this means we want to run a sub-process with both its input and output attached to pipes. We can't handle that easily from a single parent process using straightforward code such as the transport_write_message() function because the subprocess might not be reading its input because it is trying to write to a full output pipe. The complication of redesigning the world to handle this is too great - simpler just to run another process to do the reading of the output pipe. */ /* As this is a local transport, we are already running with the required uid/gid and current directory. Request that the new process be a process group leader, so we can kill it and all its children on a timeout. */ if ((pid = child_open(USS argv, envp, ob->umask, &fd_in, &fd_out, TRUE)) < 0) { addr->transport_return = DEFER; addr->message = string_sprintf( "Failed to create child process for %s transport: %s", tblock->name, strerror(errno)); return FALSE; } /* Now fork a process to handle the output that comes down the pipe. */ if ((outpid = fork()) < 0) { addr->basic_errno = errno; addr->transport_return = DEFER; addr->message = string_sprintf( "Failed to create process for handling output in %s transport", tblock->name); (void)close(fd_in); (void)close(fd_out); return FALSE; } /* This is the code for the output-handling subprocess. Read from the pipe in chunks, and write to the return file if one is provided. Keep track of the number of bytes handled. If the limit is exceeded, try to kill the subprocess group, and in any case close the pipe and exit, which should cause the subprocess to fail. */ if (outpid == 0) { int count = 0; (void)close(fd_in); set_process_info("reading output from |%s", cmd); while ((rc = read(fd_out, big_buffer, big_buffer_size)) > 0) { if (addr->return_file >= 0) if(write(addr->return_file, big_buffer, rc) != rc) DEBUG(D_transport) debug_printf("Problem writing to return_file\n"); count += rc; if (count > ob->max_output) { DEBUG(D_transport) debug_printf("Too much output from pipe - killed\n"); if (addr->return_file >= 0) { uschar *message = US"\n\n*** Too much output - remainder discarded ***\n"; rc = Ustrlen(message); if(write(addr->return_file, message, rc) != rc) DEBUG(D_transport) debug_printf("Problem writing to return_file\n"); } killpg(pid, SIGKILL); break; } } (void)close(fd_out); _exit(0); } (void)close(fd_out); /* Not used in this process */ /* Carrying on now with the main parent process. Attempt to write the message to it down the pipe. It is a fallacy to think that you can detect write errors when the sub-process fails to read the pipe. The parent process may complete writing and close the pipe before the sub-process completes. We could sleep a bit here to let the sub-process get going, but it may still not complete. So we ignore all writing errors. (When in the test harness, we do do a short sleep so any debugging output is likely to be in the same order.) */ if (running_in_test_harness) millisleep(500); DEBUG(D_transport) debug_printf("Writing message to pipe\n"); /* Arrange to time out writes if there is a timeout set. */ if (timeout > 0) { sigalrm_seen = FALSE; transport_write_timeout = timeout; } /* Reset the counter of bytes written */ transport_count = 0; /* First write any configured prefix information */ if (ob->message_prefix != NULL) { uschar *prefix = expand_string(ob->message_prefix); if (prefix == NULL) { addr->transport_return = search_find_defer? DEFER : PANIC; addr->message = string_sprintf("Expansion of \"%s\" (prefix for %s " "transport) failed: %s", ob->message_prefix, tblock->name, expand_string_message); return FALSE; } if (!transport_write_block(fd_in, prefix, Ustrlen(prefix))) goto END_WRITE; } /* If the use_bsmtp option is set, we need to write SMTP prefix information. The various different values for batching are handled outside; if there is more than one address available here, all must be included. Force SMTP dot-handling. */ if (ob->use_bsmtp) { address_item *a; if (!transport_write_string(fd_in, "MAIL FROM:<%s>%s", return_path, eol)) goto END_WRITE; for (a = addr; a != NULL; a = a->next) { if (!transport_write_string(fd_in, "RCPT TO:<%s>%s", transport_rcpt_address(a, tblock->rcpt_include_affixes), eol)) goto END_WRITE; } if (!transport_write_string(fd_in, "DATA%s", eol)) goto END_WRITE; } /* Now the actual message - the options were set at initialization time */ if (!transport_write_message(addr, fd_in, ob->options, 0, tblock->add_headers, tblock->remove_headers, ob->check_string, ob->escape_string, tblock->rewrite_rules, tblock->rewrite_existflags)) goto END_WRITE; /* Now any configured suffix */ if (ob->message_suffix != NULL) { uschar *suffix = expand_string(ob->message_suffix); if (suffix == NULL) { addr->transport_return = search_find_defer? DEFER : PANIC; addr->message = string_sprintf("Expansion of \"%s\" (suffix for %s " "transport) failed: %s", ob->message_suffix, tblock->name, expand_string_message); return FALSE; } if (!transport_write_block(fd_in, suffix, Ustrlen(suffix))) goto END_WRITE; } /* If local_smtp, write the terminating dot. */ if (ob->use_bsmtp && !transport_write_string(fd_in, ".%s", eol)) goto END_WRITE; /* Flag all writing completed successfully. */ written_ok = TRUE; /* Come here if there are errors during writing. */ END_WRITE: /* OK, the writing is now all done. Close the pipe. */ (void) close(fd_in); /* Handle errors during writing. For timeouts, set the timeout for waiting for the child process to 1 second. If the process at the far end of the pipe died without reading all of it, we expect an EPIPE error, which should be ignored. We used also to ignore WRITEINCOMPLETE but the writing function is now cleverer at handling OS where the death of a pipe doesn't give EPIPE immediately. See comments therein. */ if (!written_ok) { if (errno == ETIMEDOUT) { addr->message = string_sprintf("%stimeout while writing to pipe", transport_filter_timed_out? "transport filter " : ""); addr->transport_return = ob->timeout_defer? DEFER : FAIL; timeout = 1; } else if (errno == EPIPE) { debug_printf("transport error EPIPE ignored\n"); } else { addr->transport_return = PANIC; addr->basic_errno = errno; if (errno == ERRNO_CHHEADER_FAIL) addr->message = string_sprintf("Failed to expand headers_add or headers_remove: %s", expand_string_message); else if (errno == ERRNO_FILTER_FAIL) addr->message = string_sprintf("Transport filter process failed (%d)%s", addr->more_errno, (addr->more_errno == EX_EXECFAILED)? ": unable to execute command" : ""); else if (errno == ERRNO_WRITEINCOMPLETE) addr->message = string_sprintf("Failed repeatedly to write data"); else addr->message = string_sprintf("Error %d", errno); return FALSE; } } /* Wait for the child process to complete and take action if the returned status is nonzero. The timeout will be just 1 second if any of the writes above timed out. */ if ((rc = child_close(pid, timeout)) != 0) { uschar *tmsg = (addr->message == NULL)? US"" : string_sprintf(" (preceded by %s)", addr->message); /* The process did not complete in time; kill its process group and fail the delivery. It appears to be necessary to kill the output process too, as otherwise it hangs on for some time if the actual pipe process is sleeping. (At least, that's what I observed on Solaris 2.5.1.) Since we are failing the delivery, that shouldn't cause any problem. */ if (rc == -256) { killpg(pid, SIGKILL); kill(outpid, SIGKILL); addr->transport_return = ob->timeout_defer? DEFER : FAIL; addr->message = string_sprintf("pipe delivery process timed out%s", tmsg); } /* Wait() failed. */ else if (rc == -257) { addr->transport_return = PANIC; addr->message = string_sprintf("Wait() failed for child process of %s " "transport: %s%s", tblock->name, strerror(errno), tmsg); } /* Since the transport_filter timed out we assume it has sent the child process a malformed or incomplete data stream. Kill off the child process and prevent checking its exit status as it will has probably exited in error. This prevents the transport_filter timeout message from getting overwritten by the exit error which is not the cause of the problem. */ else if (transport_filter_timed_out) { killpg(pid, SIGKILL); kill(outpid, SIGKILL); } /* Either the process completed, but yielded a non-zero (necessarily positive) status, or the process was terminated by a signal (rc will contain the negation of the signal number). Treat killing by signal as failure unless status is being ignored. By default, the message is bounced back, unless freeze_signal is set, in which case it is frozen instead. */ else if (rc < 0) { if (ob->freeze_signal) { addr->transport_return = DEFER; addr->special_action = SPECIAL_FREEZE; addr->message = string_sprintf("Child process of %s transport (running " "command \"%s\") was terminated by signal %d (%s)%s", tblock->name, cmd, -rc, os_strsignal(-rc), tmsg); } else if (!ob->ignore_status) { addr->transport_return = FAIL; addr->message = string_sprintf("Child process of %s transport (running " "command \"%s\") was terminated by signal %d (%s)%s", tblock->name, cmd, -rc, os_strsignal(-rc), tmsg); } } /* For positive values (process terminated with non-zero status), we need a status code to request deferral. A number of systems contain the following line in sysexits.h: #define EX_TEMPFAIL 75 with the description EX_TEMPFAIL -- temporary failure, indicating something that is not really an error. In sendmail, this means that a mailer (e.g.) could not create a connection, and the request should be reattempted later. Based on this, we use exit code EX_TEMPFAIL as a default to mean "defer" when not ignoring the returned status. However, there is now an option that contains a list of temporary codes, with TEMPFAIL and CANTCREAT as defaults. Another case that needs special treatment is if execve() failed (typically the command that was given is a non-existent path). By default this is treated as just another failure, but if freeze_exec_fail is set, the reaction is to freeze the message rather than bounce the address. Exim used to signal this failure with EX_UNAVAILABLE, which is definined in many systems as #define EX_UNAVAILABLE 69 with the description EX_UNAVAILABLE -- A service is unavailable. This can occur if a support program or file does not exist. This can also be used as a catchall message when something you wanted to do doesn't work, but you don't know why. However, this can be confused with a command that actually returns 69 because something *it* wanted is unavailable. At release 4.21, Exim was changed to use return code 127 instead, because this is what the shell returns when it is unable to exec a command. We define it as EX_EXECFAILED, and use it in child.c to signal execve() failure and other unexpected failures such as setuid() not working - though that won't be the case here because we aren't changing uid. */ else { /* Always handle execve() failure specially if requested to */ if (ob->freeze_exec_fail && (rc == EX_EXECFAILED)) { addr->transport_return = DEFER; addr->special_action = SPECIAL_FREEZE; addr->message = string_sprintf("pipe process failed to exec \"%s\"%s", cmd, tmsg); } /* Otherwise take action only if not ignoring status */ else if (!ob->ignore_status) { uschar *ss; int size, ptr, i; /* If temp_errors is "*" all codes are temporary. Initializion checks that it's either "*" or a list of numbers. If not "*", scan the list of temporary failure codes; if any match, the result is DEFER. */ if (ob->temp_errors[0] == '*') addr->transport_return = DEFER; else { const uschar *s = ob->temp_errors; uschar *p; uschar buffer[64]; int sep = 0; addr->transport_return = FAIL; while ((p = string_nextinlist(&s,&sep,buffer,sizeof(buffer)))) if (rc == Uatoi(p)) { addr->transport_return = DEFER; break; } } /* Ensure the message contains the expanded command and arguments. This doesn't have to be brilliantly efficient - it is an error situation. */ addr->message = string_sprintf("Child process of %s transport returned " "%d", tblock->name, rc); ptr = Ustrlen(addr->message); size = ptr + 1; /* If the return code is > 128, it often means that a shell command was terminated by a signal. */ ss = (rc > 128)? string_sprintf("(could mean shell command ended by signal %d (%s))", rc-128, os_strsignal(rc-128)) : US os_strexit(rc); if (*ss != 0) { addr->message = string_cat(addr->message, &size, &ptr, US" ", 1); addr->message = string_cat(addr->message, &size, &ptr, ss, Ustrlen(ss)); } /* Now add the command and arguments */ addr->message = string_cat(addr->message, &size, &ptr, US" from command:", 14); for (i = 0; i < sizeof(argv)/sizeof(int *) && argv[i] != NULL; i++) { BOOL quote = FALSE; addr->message = string_cat(addr->message, &size, &ptr, US" ", 1); if (Ustrpbrk(argv[i], " \t") != NULL) { quote = TRUE; addr->message = string_cat(addr->message, &size, &ptr, US"\"", 1); } addr->message = string_cat(addr->message, &size, &ptr, argv[i], Ustrlen(argv[i])); if (quote) addr->message = string_cat(addr->message, &size, &ptr, US"\"", 1); } /* Add previous filter timeout message, if present. */ if (*tmsg != 0) addr->message = string_cat(addr->message, &size, &ptr, tmsg, Ustrlen(tmsg)); addr->message[ptr] = 0; /* Ensure concatenated string terminated */ } } } /* Ensure all subprocesses (in particular, the output handling process) are complete before we pass this point. */ while (wait(&rc) >= 0); DEBUG(D_transport) debug_printf("%s transport yielded %d\n", tblock->name, addr->transport_return); /* If there has been a problem, the message in addr->message contains details of the pipe command. We don't want to expose these to the world, so we set up something bland to return to the sender. */ if (addr->transport_return != OK) addr->user_message = US"local delivery failed"; return FALSE; }
static int dbmjz_find(void *handle, uschar *filename, const uschar *keystring, int length, uschar **result, uschar **errmsg, BOOL *do_cache) { uschar *key_item, *key_buffer, *key_p; const uschar *key_elems = keystring; int buflen, bufleft, key_item_len, sep = 0; /* To a first approximation, the size of the lookup key needs to be about, or less than, the length of the delimited list passed in + 1. */ buflen = length + 3; key_buffer = store_get(buflen); key_buffer[0] = '\0'; key_p = key_buffer; bufleft = buflen; /* In all cases of an empty list item, we can set 1 and advance by 1 and then pick up the trailing NUL from the previous list item, EXCEPT when at the beginning of the output string, in which case we need to supply that NUL ourselves. */ while ((key_item = string_nextinlist(&key_elems, &sep, key_p, bufleft)) != NULL) { key_item_len = Ustrlen(key_item) + 1; if (key_item_len == 1) { key_p[0] = '\0'; if (key_p == key_buffer) { key_p[1] = '\0'; key_item_len += 1; } } bufleft -= key_item_len; if (bufleft <= 0) { /* The string_nextinlist() will stop at buffer size, but we should always have at least 1 character extra, so some assumption has failed. */ *errmsg = string_copy(US"Ran out of buffer space for joining elements"); return DEFER; } key_p += key_item_len; } if (key_p == key_buffer) { *errmsg = string_copy(US"empty list key"); return FAIL; } /* We do not pass in the final NULL; if needed, the list should include an empty element to put one in. Boundary: key length 1, is a NULL */ key_item_len = key_p - key_buffer - 1; DEBUG(D_lookup) debug_printf("NUL-joined key length: %d\n", key_item_len); /* beware that dbmdb_find() adds 1 to length to get back terminating NUL, so because we've calculated the real length, we need to subtract one more here */ return dbmdb_find(handle, filename, key_buffer, key_item_len - 1, result, errmsg, do_cache); }
int mime_regex(uschar **listptr) { int sep = 0; uschar *list = *listptr; uschar *regex_string; uschar regex_string_buffer[1024]; pcre *re; pcre_list *re_list_head = NULL; pcre_list *re_list_item; const char *pcre_error; int pcre_erroffset; FILE *f; uschar *mime_subject = NULL; int mime_subject_len = 0; /* reset expansion variable */ regex_match_string = NULL; /* precompile our regexes */ while ((regex_string = string_nextinlist(&list, &sep, regex_string_buffer, sizeof(regex_string_buffer))) != NULL) { /* parse option */ if ( (strcmpic(regex_string,US"false") == 0) || (Ustrcmp(regex_string,"0") == 0) ) { /* explicitly no matching */ continue; }; /* compile our regular expression */ re = pcre_compile( CS regex_string, 0, &pcre_error, &pcre_erroffset, NULL ); if (re == NULL) { log_write(0, LOG_MAIN, "regex acl condition warning - error in regex '%s': %s at offset %d, skipped.", regex_string, pcre_error, pcre_erroffset); continue; } else { re_list_item = store_get(sizeof(pcre_list)); re_list_item->re = re; re_list_item->pcre_text = string_copy(regex_string); re_list_item->next = re_list_head; re_list_head = re_list_item; }; }; /* no regexes -> nothing to do */ if (re_list_head == NULL) { return FAIL; }; /* check if the file is already decoded */ if (mime_decoded_filename == NULL) { uschar *empty = US""; /* no, decode it first */ mime_decode(&empty); if (mime_decoded_filename == NULL) { /* decoding failed */ log_write(0, LOG_MAIN, "mime_regex acl condition warning - could not decode MIME part to file."); return DEFER; }; }; /* open file */ f = fopen(CS mime_decoded_filename, "rb"); if (f == NULL) { /* open failed */ log_write(0, LOG_MAIN, "mime_regex acl condition warning - can't open '%s' for reading.", mime_decoded_filename); return DEFER; }; /* get 32k memory */ mime_subject = (uschar *)store_get(32767); /* read max 32k chars from file */ mime_subject_len = fread(mime_subject, 1, 32766, f); re_list_item = re_list_head; do { /* try matcher on the mmapped file */ debug_printf("Matching '%s'\n", re_list_item->pcre_text); if (pcre_exec(re_list_item->re, NULL, CS mime_subject, mime_subject_len, 0, 0, NULL, 0) >= 0) { Ustrncpy(regex_match_string_buffer, re_list_item->pcre_text, 1023); regex_match_string = regex_match_string_buffer; (void)fclose(f); return OK; }; re_list_item = re_list_item->next; } while (re_list_item != NULL); (void)fclose(f); /* no matches ... */ return FAIL; }
uschar *dkim_exim_sign(int dkim_fd, uschar *dkim_private_key, uschar *dkim_domain, uschar *dkim_selector, uschar *dkim_canon, uschar *dkim_sign_headers) { int sep = 0; uschar *seen_items = NULL; int seen_items_size = 0; int seen_items_offset = 0; uschar itembuf[256]; uschar *dkim_canon_expanded; uschar *dkim_sign_headers_expanded; uschar *dkim_private_key_expanded; pdkim_ctx *ctx = NULL; uschar *rc = NULL; uschar *sigbuf = NULL; int sigsize = 0; int sigptr = 0; pdkim_signature *signature; int pdkim_canon; int pdkim_rc; int sread; char buf[4096]; int save_errno = 0; int old_pool = store_pool; store_pool = POOL_MAIN; dkim_domain = expand_string(dkim_domain); if (dkim_domain == NULL) { /* expansion error, do not send message. */ log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand " "dkim_domain: %s", expand_string_message); rc = NULL; goto CLEANUP; } /* Set $dkim_domain expansion variable to each unique domain in list. */ while ((dkim_signing_domain = string_nextinlist(&dkim_domain, &sep, itembuf, sizeof(itembuf))) != NULL) { if (!dkim_signing_domain || (dkim_signing_domain[0] == '\0')) continue; /* Only sign once for each domain, no matter how often it appears in the expanded list. */ if (seen_items != NULL) { uschar *seen_items_list = seen_items; if (match_isinlist(dkim_signing_domain, &seen_items_list,0,NULL,NULL,MCL_STRING,TRUE,NULL) == OK) continue; seen_items = string_append(seen_items,&seen_items_size,&seen_items_offset,1,":"); } seen_items = string_append(seen_items,&seen_items_size,&seen_items_offset,1,dkim_signing_domain); seen_items[seen_items_offset] = '\0'; /* Set up $dkim_selector expansion variable. */ dkim_signing_selector = expand_string(dkim_selector); if (dkim_signing_selector == NULL) { log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand " "dkim_selector: %s", expand_string_message); rc = NULL; goto CLEANUP; } /* Get canonicalization to use */ dkim_canon_expanded = expand_string(dkim_canon?dkim_canon:US"relaxed"); if (dkim_canon_expanded == NULL) { /* expansion error, do not send message. */ log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand " "dkim_canon: %s", expand_string_message); rc = NULL; goto CLEANUP; } if (Ustrcmp(dkim_canon_expanded, "relaxed") == 0) pdkim_canon = PDKIM_CANON_RELAXED; else if (Ustrcmp(dkim_canon_expanded, "simple") == 0) pdkim_canon = PDKIM_CANON_SIMPLE; else { log_write(0, LOG_MAIN, "DKIM: unknown canonicalization method '%s', defaulting to 'relaxed'.\n",dkim_canon_expanded); pdkim_canon = PDKIM_CANON_RELAXED; } if (dkim_sign_headers) { dkim_sign_headers_expanded = expand_string(dkim_sign_headers); if (dkim_sign_headers_expanded == NULL) { log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand " "dkim_sign_headers: %s", expand_string_message); rc = NULL; goto CLEANUP; } } else { /* pass NULL, which means default header list */ dkim_sign_headers_expanded = NULL; } /* Get private key to use. */ dkim_private_key_expanded = expand_string(dkim_private_key); if (dkim_private_key_expanded == NULL) { log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand " "dkim_private_key: %s", expand_string_message); rc = NULL; goto CLEANUP; } if ( (Ustrlen(dkim_private_key_expanded) == 0) || (Ustrcmp(dkim_private_key_expanded,"0") == 0) || (Ustrcmp(dkim_private_key_expanded,"false") == 0) ) { /* don't sign, but no error */ continue; } if (dkim_private_key_expanded[0] == '/') { int privkey_fd = 0; /* Looks like a filename, load the private key. */ memset(big_buffer,0,big_buffer_size); privkey_fd = open(CS dkim_private_key_expanded,O_RDONLY); if (privkey_fd < 0) { log_write(0, LOG_MAIN|LOG_PANIC, "unable to open " "private key file for reading: %s", dkim_private_key_expanded); rc = NULL; goto CLEANUP; } if (read(privkey_fd,big_buffer,(big_buffer_size-2)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, "unable to read private key file: %s", dkim_private_key_expanded); rc = NULL; goto CLEANUP; } (void)close(privkey_fd); dkim_private_key_expanded = big_buffer; } ctx = pdkim_init_sign(PDKIM_INPUT_SMTP, (char *)dkim_signing_domain, (char *)dkim_signing_selector, (char *)dkim_private_key_expanded ); pdkim_set_debug_stream(ctx,debug_file); pdkim_set_optional(ctx, (char *)dkim_sign_headers_expanded, NULL, pdkim_canon, pdkim_canon, -1, PDKIM_ALGO_RSA_SHA256, 0, 0); lseek(dkim_fd, 0, SEEK_SET); while((sread = read(dkim_fd,&buf,4096)) > 0) { if (pdkim_feed(ctx,buf,sread) != PDKIM_OK) { rc = NULL; goto CLEANUP; } } /* Handle failed read above. */ if (sread == -1) { debug_printf("DKIM: Error reading -K file.\n"); save_errno = errno; rc = NULL; goto CLEANUP; } pdkim_rc = pdkim_feed_finish(ctx,&signature); if (pdkim_rc != PDKIM_OK) { log_write(0, LOG_MAIN|LOG_PANIC, "DKIM: signing failed (RC %d)", pdkim_rc); rc = NULL; goto CLEANUP; } sigbuf = string_append(sigbuf, &sigsize, &sigptr, 2, US signature->signature_header, US"\r\n"); pdkim_free_ctx(ctx); ctx = NULL; } if (sigbuf != NULL) { sigbuf[sigptr] = '\0'; rc = sigbuf; } else rc = US""; CLEANUP: if (ctx != NULL) pdkim_free_ctx(ctx); store_pool = old_pool; errno = save_errno; return rc; }
static int dnsdb_find(void *handle, uschar *filename, const uschar *keystring, int length, uschar **result, uschar **errmsg, uint *do_cache) { int rc; int size = 256; int ptr = 0; int sep = 0; int defer_mode = PASS; int dnssec_mode = OK; int save_retrans = dns_retrans; int save_retry = dns_retry; int type; int failrc = FAIL; const uschar *outsep = CUS"\n"; const uschar *outsep2 = NULL; uschar *equals, *domain, *found; /* Because we're the working in the search pool, we try to reclaim as much store as possible later, so we preallocate the result here */ uschar *yield = store_get(size); dns_record *rr; dns_answer dnsa; dns_scan dnss; handle = handle; /* Keep picky compilers happy */ filename = filename; length = length; do_cache = do_cache; /* If the string starts with '>' we change the output separator. If it's followed by ';' or ',' we set the TXT output separator. */ while (isspace(*keystring)) keystring++; if (*keystring == '>') { outsep = keystring + 1; keystring += 2; if (*keystring == ',') { outsep2 = keystring + 1; keystring += 2; } else if (*keystring == ';') { outsep2 = US""; keystring++; } while (isspace(*keystring)) keystring++; } /* Check for a modifier keyword. */ for (;;) { if (strncmpic(keystring, US"defer_", 6) == 0) { keystring += 6; if (strncmpic(keystring, US"strict", 6) == 0) { defer_mode = DEFER; keystring += 6; } else if (strncmpic(keystring, US"lax", 3) == 0) { defer_mode = PASS; keystring += 3; } else if (strncmpic(keystring, US"never", 5) == 0) { defer_mode = OK; keystring += 5; } else { *errmsg = US"unsupported dnsdb defer behaviour"; return DEFER; } } else if (strncmpic(keystring, US"dnssec_", 7) == 0) { keystring += 7; if (strncmpic(keystring, US"strict", 6) == 0) { dnssec_mode = DEFER; keystring += 6; } else if (strncmpic(keystring, US"lax", 3) == 0) { dnssec_mode = PASS; keystring += 3; } else if (strncmpic(keystring, US"never", 5) == 0) { dnssec_mode = OK; keystring += 5; } else { *errmsg = US"unsupported dnsdb dnssec behaviour"; return DEFER; } } else if (strncmpic(keystring, US"retrans_", 8) == 0) { int timeout_sec; if ((timeout_sec = readconf_readtime(keystring += 8, ',', FALSE)) <= 0) { *errmsg = US"unsupported dnsdb timeout value"; return DEFER; } dns_retrans = timeout_sec; while (*keystring != ',') keystring++; } else if (strncmpic(keystring, US"retry_", 6) == 0) { int retries; if ((retries = (int)strtol(CCS keystring + 6, CSS &keystring, 0)) < 0) { *errmsg = US"unsupported dnsdb retry count"; return DEFER; } dns_retry = retries; } else break; while (isspace(*keystring)) keystring++; if (*keystring++ != ',') { *errmsg = US"dnsdb modifier syntax error"; return DEFER; } while (isspace(*keystring)) keystring++; } /* Figure out the "type" value if it is not T_TXT. If the keystring contains an = this must be preceded by a valid type name. */ type = T_TXT; if ((equals = Ustrchr(keystring, '=')) != NULL) { int i, len; uschar *tend = equals; while (tend > keystring && isspace(tend[-1])) tend--; len = tend - keystring; for (i = 0; i < nelem(type_names); i++) if (len == Ustrlen(type_names[i]) && strncmpic(keystring, US type_names[i], len) == 0) { type = type_values[i]; break; } if (i >= nelem(type_names)) { *errmsg = US"unsupported DNS record type"; return DEFER; } keystring = equals + 1; while (isspace(*keystring)) keystring++; } /* Initialize the resolver in case this is the first time it has been used. */ dns_init(FALSE, FALSE, dnssec_mode != OK); /* The remainder of the string must be a list of domains. As long as the lookup for at least one of them succeeds, we return success. Failure means that none of them were found. The original implementation did not support a list of domains. Adding the list feature is compatible, except in one case: when PTR records are being looked up for a single IPv6 address. Fortunately, we can hack in a compatibility feature here: If the type is PTR and no list separator is specified, and the entire remaining string is valid as an IP address, set an impossible separator so that it is treated as one item. */ if (type == T_PTR && keystring[0] != '<' && string_is_ip_address(keystring, NULL) != 0) sep = -1; /* SPF strings should be concatenated without a separator, thus make it the default if not defined (see RFC 4408 section 3.1.3). Multiple SPF records are forbidden (section 3.1.2) but are currently not handled specially, thus they are concatenated with \n by default. MX priority and value are space-separated by default. SRV and TLSA record parts are space-separated by default. */ if (!outsep2) switch(type) { case T_SPF: outsep2 = US""; break; case T_SRV: case T_MX: case T_TLSA: outsep2 = US" "; break; } /* Now scan the list and do a lookup for each item */ while ((domain = string_nextinlist(&keystring, &sep, NULL, 0))) { uschar rbuffer[256]; int searchtype = (type == T_CSA)? T_SRV : /* record type we want */ (type == T_MXH)? T_MX : (type == T_ZNS)? T_NS : type; /* If the type is PTR or CSA, we have to construct the relevant magic lookup key if the original is an IP address (some experimental protocols are using PTR records for different purposes where the key string is a host name, and Exim's extended CSA can be keyed by domains or IP addresses). This code for doing the reversal is now in a separate function. */ if ((type == T_PTR || type == T_CSA) && string_is_ip_address(domain, NULL) != 0) { dns_build_reverse(domain, rbuffer); domain = rbuffer; } do { DEBUG(D_lookup) debug_printf("dnsdb key: %s\n", domain); /* Do the lookup and sort out the result. There are four special types that are handled specially: T_CSA, T_ZNS, T_ADDRESSES and T_MXH. The first two are handled in a special lookup function so that the facility could be used from other parts of the Exim code. T_ADDRESSES is handled by looping over the types of A lookup. T_MXH affects only what happens later on in this function, but for tidiness it is handled by the "special". If the lookup fails, continue with the next domain. In the case of DEFER, adjust the final "nothing found" result, but carry on to the next domain. */ found = domain; #if HAVE_IPV6 if (type == T_ADDRESSES) /* NB cannot happen unless HAVE_IPV6 */ { if (searchtype == T_ADDRESSES) searchtype = T_AAAA; else if (searchtype == T_AAAA) searchtype = T_A; rc = dns_special_lookup(&dnsa, domain, searchtype, CUSS &found); } else #endif rc = dns_special_lookup(&dnsa, domain, type, CUSS &found); lookup_dnssec_authenticated = dnssec_mode==OK ? NULL : dns_is_secure(&dnsa) ? US"yes" : US"no"; if (rc == DNS_NOMATCH || rc == DNS_NODATA) continue; if ( rc != DNS_SUCCEED || (dnssec_mode == DEFER && !dns_is_secure(&dnsa)) ) { if (defer_mode == DEFER) { dns_retrans = save_retrans; dns_retry = save_retry; dns_init(FALSE, FALSE, FALSE); /* clr dnssec bit */ return DEFER; /* always defer */ } if (defer_mode == PASS) failrc = DEFER; /* defer only if all do */ continue; /* treat defer as fail */ } /* Search the returned records */ for (rr = dns_next_rr(&dnsa, &dnss, RESET_ANSWERS); rr != NULL; rr = dns_next_rr(&dnsa, &dnss, RESET_NEXT)) { if (rr->type != searchtype) continue; if (*do_cache > rr->ttl) *do_cache = rr->ttl; if (type == T_A || type == T_AAAA || type == T_ADDRESSES) { dns_address *da; for (da = dns_address_from_rr(&dnsa, rr); da; da = da->next) { if (ptr != 0) yield = string_catn(yield, &size, &ptr, outsep, 1); yield = string_cat(yield, &size, &ptr, da->address); } continue; } /* Other kinds of record just have one piece of data each, but there may be several of them, of course. */ if (ptr != 0) yield = string_catn(yield, &size, &ptr, outsep, 1); if (type == T_TXT || type == T_SPF) { if (outsep2 == NULL) { /* output only the first item of data */ yield = string_catn(yield, &size, &ptr, (uschar *)(rr->data+1), (rr->data)[0]); } else { /* output all items */ int data_offset = 0; while (data_offset < rr->size) { uschar chunk_len = (rr->data)[data_offset++]; if (outsep2[0] != '\0' && data_offset != 1) yield = string_catn(yield, &size, &ptr, outsep2, 1); yield = string_catn(yield, &size, &ptr, US ((rr->data)+data_offset), chunk_len); data_offset += chunk_len; } } } else if (type == T_TLSA) { uint8_t usage, selector, matching_type; uint16_t i, payload_length; uschar s[MAX_TLSA_EXPANDED_SIZE]; uschar * sp = s; uschar * p = US rr->data; usage = *p++; selector = *p++; matching_type = *p++; /* What's left after removing the first 3 bytes above */ payload_length = rr->size - 3; sp += sprintf(CS s, "%d%c%d%c%d%c", usage, *outsep2, selector, *outsep2, matching_type, *outsep2); /* Now append the cert/identifier, one hex char at a time */ for (i=0; i < payload_length && sp-s < (MAX_TLSA_EXPANDED_SIZE - 4); i++) sp += sprintf(CS sp, "%02x", (unsigned char)p[i]); yield = string_cat(yield, &size, &ptr, s); } else /* T_CNAME, T_CSA, T_MX, T_MXH, T_NS, T_PTR, T_SOA, T_SRV */ { int priority, weight, port; uschar s[264]; uschar * p = US rr->data; switch (type) { case T_MXH: /* mxh ignores the priority number and includes only the hostnames */ GETSHORT(priority, p); break; case T_MX: GETSHORT(priority, p); sprintf(CS s, "%d%c", priority, *outsep2); yield = string_cat(yield, &size, &ptr, s); break; case T_SRV: GETSHORT(priority, p); GETSHORT(weight, p); GETSHORT(port, p); sprintf(CS s, "%d%c%d%c%d%c", priority, *outsep2, weight, *outsep2, port, *outsep2); yield = string_cat(yield, &size, &ptr, s); break; case T_CSA: /* See acl_verify_csa() for more comments about CSA. */ GETSHORT(priority, p); GETSHORT(weight, p); GETSHORT(port, p); if (priority != 1) continue; /* CSA version must be 1 */ /* If the CSA record we found is not the one we asked for, analyse the subdomain assertions in the port field, else analyse the direct authorization status in the weight field. */ if (Ustrcmp(found, domain) != 0) { if (port & 1) *s = 'X'; /* explicit authorization required */ else *s = '?'; /* no subdomain assertions here */ } else { if (weight < 2) *s = 'N'; /* not authorized */ else if (weight == 2) *s = 'Y'; /* authorized */ else if (weight == 3) *s = '?'; /* unauthorizable */ else continue; /* invalid */ } s[1] = ' '; yield = string_catn(yield, &size, &ptr, s, 2); break; default: break; } /* GETSHORT() has advanced the pointer to the target domain. */ rc = dn_expand(dnsa.answer, dnsa.answer + dnsa.answerlen, p, (DN_EXPAND_ARG4_TYPE)s, sizeof(s)); /* If an overlong response was received, the data will have been truncated and dn_expand may fail. */ if (rc < 0) { log_write(0, LOG_MAIN, "host name alias list truncated: type=%s " "domain=%s", dns_text_type(type), domain); break; } else yield = string_cat(yield, &size, &ptr, s); if (type == T_SOA && outsep2 != NULL) { unsigned long serial, refresh, retry, expire, minimum; p += rc; yield = string_catn(yield, &size, &ptr, outsep2, 1); rc = dn_expand(dnsa.answer, dnsa.answer + dnsa.answerlen, p, (DN_EXPAND_ARG4_TYPE)s, sizeof(s)); if (rc < 0) { log_write(0, LOG_MAIN, "responsible-mailbox truncated: type=%s " "domain=%s", dns_text_type(type), domain); break; } else yield = string_cat(yield, &size, &ptr, s); p += rc; GETLONG(serial, p); GETLONG(refresh, p); GETLONG(retry, p); GETLONG(expire, p); GETLONG(minimum, p); sprintf(CS s, "%c%lu%c%lu%c%lu%c%lu%c%lu", *outsep2, serial, *outsep2, refresh, *outsep2, retry, *outsep2, expire, *outsep2, minimum); yield = string_cat(yield, &size, &ptr, s); } } } /* Loop for list of returned records */ /* Loop for set of A-lookup types */ } while (type == T_ADDRESSES && searchtype != T_A); } /* Loop for list of domains */ /* Reclaim unused memory */ store_reset(yield + ptr + 1); /* If ptr == 0 we have not found anything. Otherwise, insert the terminating zero and return the result. */ dns_retrans = save_retrans; dns_retry = save_retry; dns_init(FALSE, FALSE, FALSE); /* clear the dnssec bit for getaddrbyname */ if (ptr == 0) return failrc; yield[ptr] = 0; *result = yield; return OK; }
int auth_call_radius(const uschar *s, uschar **errptr) { uschar *user; const uschar *radius_args = s; int result; int sep = 0; #ifdef RADIUS_LIB_RADLIB struct rad_handle *h; #else #ifdef RADIUS_LIB_RADIUSCLIENTNEW rc_handle *h; #endif VALUE_PAIR *send = NULL; VALUE_PAIR *received; unsigned int service = PW_AUTHENTICATE_ONLY; char msg[4096]; #endif user = string_nextinlist(&radius_args, &sep, big_buffer, big_buffer_size); if (user == NULL) user = US""; DEBUG(D_auth) debug_printf("Running RADIUS authentication for user \"%s\" " "and \"%s\"\n", user, radius_args); *errptr = NULL; /* Authenticate using the radiusclient library */ #ifndef RADIUS_LIB_RADLIB rc_openlog("exim"); #ifdef RADIUS_LIB_RADIUSCLIENT if (rc_read_config(RADIUS_CONFIG_FILE) != 0) *errptr = string_sprintf("RADIUS: can't open %s", RADIUS_CONFIG_FILE); else if (rc_read_dictionary(rc_conf_str("dictionary")) != 0) *errptr = string_sprintf("RADIUS: can't read dictionary"); else if (rc_avpair_add(&send, PW_USER_NAME, user, 0) == NULL) *errptr = string_sprintf("RADIUS: add user name failed\n"); else if (rc_avpair_add(&send, PW_USER_PASSWORD, CS radius_args, 0) == NULL) *errptr = string_sprintf("RADIUS: add password failed\n"); else if (rc_avpair_add(&send, PW_SERVICE_TYPE, &service, 0) == NULL) *errptr = string_sprintf("RADIUS: add service type failed\n"); #else /* RADIUS_LIB_RADIUSCLIENT unset => RADIUS_LIB_RADIUSCLIENT2 */ if ((h = rc_read_config(RADIUS_CONFIG_FILE)) == NULL) *errptr = string_sprintf("RADIUS: can't open %s", RADIUS_CONFIG_FILE); else if (rc_read_dictionary(h, rc_conf_str(h, "dictionary")) != 0) *errptr = string_sprintf("RADIUS: can't read dictionary"); else if (rc_avpair_add(h, &send, PW_USER_NAME, user, Ustrlen(user), 0) == NULL) *errptr = string_sprintf("RADIUS: add user name failed\n"); else if (rc_avpair_add(h, &send, PW_USER_PASSWORD, CS radius_args, Ustrlen(radius_args), 0) == NULL) *errptr = string_sprintf("RADIUS: add password failed\n"); else if (rc_avpair_add(h, &send, PW_SERVICE_TYPE, &service, 0, 0) == NULL) *errptr = string_sprintf("RADIUS: add service type failed\n"); #endif /* RADIUS_LIB_RADIUSCLIENT */ if (*errptr != NULL) { DEBUG(D_auth) debug_printf("%s\n", *errptr); return ERROR; } #ifdef RADIUS_LIB_RADIUSCLIENT result = rc_auth(0, send, &received, msg); #else result = rc_auth(h, 0, send, &received, msg); #endif DEBUG(D_auth) debug_printf("RADIUS code returned %d\n", result); switch (result) { case OK_RC: return OK; case REJECT_RC: case ERROR_RC: return FAIL; case TIMEOUT_RC: *errptr = US"RADIUS: timed out"; return ERROR; default: case BADRESP_RC: *errptr = string_sprintf("RADIUS: unexpected response (%d)", result); return ERROR; } #else /* RADIUS_LIB_RADLIB is set */ /* Authenticate using the libradius library */ h = rad_auth_open(); if (h == NULL) { *errptr = string_sprintf("RADIUS: can't initialise libradius"); return ERROR; } if (rad_config(h, RADIUS_CONFIG_FILE) != 0 || rad_create_request(h, RAD_ACCESS_REQUEST) != 0 || rad_put_string(h, RAD_USER_NAME, CS user) != 0 || rad_put_string(h, RAD_USER_PASSWORD, CS radius_args) != 0 || rad_put_int(h, RAD_SERVICE_TYPE, RAD_AUTHENTICATE_ONLY) != 0 || rad_put_string(h, RAD_NAS_IDENTIFIER, CS primary_hostname) != 0) { *errptr = string_sprintf("RADIUS: %s", rad_strerror(h)); result = ERROR; } else { result = rad_send_request(h); switch(result) { case RAD_ACCESS_ACCEPT: result = OK; break; case RAD_ACCESS_REJECT: result = FAIL; break; case -1: *errptr = string_sprintf("RADIUS: %s", rad_strerror(h)); result = ERROR; break; default: *errptr = string_sprintf("RADIUS: unexpected response (%d)", result); result= ERROR; break; } } if (*errptr != NULL) DEBUG(D_auth) debug_printf("%s\n", *errptr); rad_close(h); return result; #endif /* RADIUS_LIB_RADLIB */ }
int eximsrs_init() { uschar *list = srs_config; uschar secret_buf[SRS_MAX_SECRET_LENGTH]; uschar *secret = NULL; uschar sbuf[4]; uschar *sbufp; /* Check if this instance of Exim has not initialized SRS */ if(srs == NULL) { int co = 0; int hashlen, maxage; BOOL usetimestamp, usehash; /* Copy config vars */ hashlen = srs_hashlength; maxage = srs_maxage; usetimestamp = srs_usetimestamp; usehash = srs_usehash; /* Pass srs_config var (overrides new config vars) */ co = 0; if(srs_config != NULL) { secret = string_nextinlist(&list, &co, secret_buf, SRS_MAX_SECRET_LENGTH); if((sbufp = string_nextinlist(&list, &co, sbuf, sizeof(sbuf))) != NULL) maxage = atoi(sbuf); if((sbufp = string_nextinlist(&list, &co, sbuf, sizeof(sbuf))) != NULL) hashlen = atoi(sbuf); if((sbufp = string_nextinlist(&list, &co, sbuf, sizeof(sbuf))) != NULL) usetimestamp = atoi(sbuf); if((sbufp = string_nextinlist(&list, &co, sbuf, sizeof(sbuf))) != NULL) usehash = atoi(sbuf); } if(srs_hashmin == -1) srs_hashmin = hashlen; /* First secret specified in secrets? */ co = 0; list = srs_secrets; if(secret == NULL || *secret == '\0') { if((secret = string_nextinlist(&list, &co, secret_buf, SRS_MAX_SECRET_LENGTH)) == NULL) { log_write(0, LOG_MAIN | LOG_PANIC, "SRS Configuration Error: No secret specified"); return DEFER; } } /* Check config */ if(maxage < 0 || maxage > 365) { log_write(0, LOG_MAIN | LOG_PANIC, "SRS Configuration Error: Invalid maximum timestamp age"); return DEFER; } if(hashlen < 1 || hashlen > 20 || srs_hashmin < 1 || srs_hashmin > 20) { log_write(0, LOG_MAIN | LOG_PANIC, "SRS Configuration Error: Invalid hash length"); return DEFER; } if((srs = srs_open(secret, Ustrlen(secret), maxage, hashlen, srs_hashmin)) == NULL) { log_write(0, LOG_MAIN | LOG_PANIC, "Failed to allocate SRS memory"); return DEFER; } srs_set_option(srs, SRS_OPTION_USETIMESTAMP, usetimestamp); srs_set_option(srs, SRS_OPTION_USEHASH, usehash); /* Extra secrets? */ while((secret = string_nextinlist(&list, &co, secret_buf, SRS_MAX_SECRET_LENGTH)) != NULL) srs_add_secret(srs, secret, (Ustrlen(secret) > SRS_MAX_SECRET_LENGTH) ? SRS_MAX_SECRET_LENGTH : Ustrlen(secret)); DEBUG(D_any) debug_printf("SRS initialized\n"); } return OK; }
int mime_decode(const uschar **listptr) { int sep = 0; const uschar *list = *listptr; uschar *option; uschar option_buffer[1024]; uschar decode_path[1024]; FILE *decode_file = NULL; long f_pos = 0; ssize_t size_counter = 0; ssize_t (*decode_function)(FILE*, FILE*, uschar*); if (mime_stream == NULL) return FAIL; f_pos = ftell(mime_stream); /* build default decode path (will exist since MBOX must be spooled up) */ (void)string_format(decode_path,1024,"%s/scan/%s",spool_directory,message_id); /* try to find 1st option */ if ((option = string_nextinlist(&list, &sep, option_buffer, sizeof(option_buffer))) != NULL) { /* parse 1st option */ if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) ) /* explicitly no decoding */ return FAIL; if (Ustrcmp(option,"default") == 0) /* explicit default path + file names */ goto DEFAULT_PATH; if (option[0] == '/') { struct stat statbuf; memset(&statbuf,0,sizeof(statbuf)); /* assume either path or path+file name */ if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) ) /* is directory, use it as decode_path */ decode_file = mime_get_decode_file(option, NULL); else /* does not exist or is a file, use as full file name */ decode_file = mime_get_decode_file(NULL, option); } else /* assume file name only, use default path */ decode_file = mime_get_decode_file(decode_path, option); } else { /* no option? patch default path */ DEFAULT_PATH: decode_file = mime_get_decode_file(decode_path, NULL); } if (!decode_file) return DEFER; /* decode according to mime type */ decode_function = !mime_content_transfer_encoding ? mime_decode_asis /* no encoding, dump as-is */ : Ustrcmp(mime_content_transfer_encoding, "base64") == 0 ? mime_decode_base64 : Ustrcmp(mime_content_transfer_encoding, "quoted-printable") == 0 ? mime_decode_qp : mime_decode_asis; /* unknown encoding type, just dump as-is */ size_counter = decode_function(mime_stream, decode_file, mime_current_boundary); clearerr(mime_stream); if (fseek(mime_stream, f_pos, SEEK_SET)) return DEFER; if (fclose(decode_file) != 0 || size_counter < 0) return DEFER; /* round up to the next KiB */ mime_content_size = (size_counter + 1023) / 1024; return OK; }
int manualroute_router_entry( router_instance *rblock, /* data for this instantiation */ address_item *addr, /* address we are working on */ struct passwd *pw, /* passwd entry after check_local_user */ int verify, /* v_none/v_recipient/v_sender/v_expn */ address_item **addr_local, /* add it to this if it's local */ address_item **addr_remote, /* add it to this if it's remote */ address_item **addr_new, /* put new addresses on here */ address_item **addr_succeed) /* put old address here on success */ { int rc, lookup_type; uschar *route_item = NULL; const uschar *options = NULL; const uschar *hostlist = NULL; const uschar *domain; uschar *newhostlist; const uschar *listptr; manualroute_router_options_block *ob = (manualroute_router_options_block *)(rblock->options_block); transport_instance *transport = NULL; BOOL individual_transport_set = FALSE; BOOL randomize = ob->hosts_randomize; addr_new = addr_new; /* Keep picky compilers happy */ addr_succeed = addr_succeed; DEBUG(D_route) debug_printf("%s router called for %s\n domain = %s\n", rblock->name, addr->address, addr->domain); /* The initialization check ensures that either route_list or route_data is set. */ if (ob->route_list != NULL) { int sep = -(';'); /* Default is semicolon */ listptr = ob->route_list; while ((route_item = string_nextinlist(&listptr, &sep, NULL, 0)) != NULL) { int rc; DEBUG(D_route) debug_printf("route_item = %s\n", route_item); if (!parse_route_item(route_item, &domain, &hostlist, &options)) continue; /* Ignore blank items */ /* Check the current domain; if it matches, break the loop */ if ((rc = match_isinlist(addr->domain, &domain, UCHAR_MAX+1, &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, CUSS &lookup_value)) == OK) break; /* If there was a problem doing the check, defer */ if (rc == DEFER) { addr->message = US"lookup defer in route_list"; return DEFER; } } if (route_item == NULL) return DECLINE; /* No pattern in the list matched */ } /* Handle a single routing item in route_data. If it expands to an empty string, decline. */ else { route_item = rf_expand_data(addr, ob->route_data, &rc); if (route_item == NULL) return rc; (void) parse_route_item(route_item, NULL, &hostlist, &options); if (hostlist[0] == 0) return DECLINE; } /* Expand the hostlist item. It may then pointing to an empty string, or to a single host or a list of hosts; options is pointing to the rest of the routelist item, which is either empty or contains various option words. */ DEBUG(D_route) debug_printf("original list of hosts = \"%s\" options = %s\n", hostlist, options); newhostlist = expand_string_copy(hostlist); lookup_value = NULL; /* Finished with */ expand_nmax = -1; /* If the expansion was forced to fail, just decline. Otherwise there is a configuration problem. */ if (newhostlist == NULL) { if (expand_string_forcedfail) return DECLINE; addr->message = string_sprintf("%s router: failed to expand \"%s\": %s", rblock->name, hostlist, expand_string_message); return DEFER; } else hostlist = newhostlist; DEBUG(D_route) debug_printf("expanded list of hosts = \"%s\" options = %s\n", hostlist, options); /* Set default lookup type and scan the options */ lookup_type = lk_default; while (*options != 0) { unsigned n; const uschar *s = options; while (*options != 0 && !isspace(*options)) options++; n = options-s; if (Ustrncmp(s, "randomize", n) == 0) randomize = TRUE; else if (Ustrncmp(s, "no_randomize", n) == 0) randomize = FALSE; else if (Ustrncmp(s, "byname", n) == 0) lookup_type = lk_byname; else if (Ustrncmp(s, "bydns", n) == 0) lookup_type = lk_bydns; else { transport_instance *t; for (t = transports; t != NULL; t = t->next) if (Ustrcmp(t->name, s) == 0) { transport = t; individual_transport_set = TRUE; break; } if (t == NULL) { s = string_sprintf("unknown routing option or transport name \"%s\"", s); log_write(0, LOG_MAIN, "Error in %s router: %s", rblock->name, s); addr->message = string_sprintf("error in router: %s", s); return DEFER; } } if (*options) { options++; while (*options != 0 && isspace(*options)) options++; } } /* Set up the errors address, if any. */ rc = rf_get_errors_address(addr, rblock, verify, &addr->prop.errors_address); if (rc != OK) return rc; /* Set up the additional and removeable headers for this address. */ rc = rf_get_munge_headers(addr, rblock, &addr->prop.extra_headers, &addr->prop.remove_headers); if (rc != OK) return rc; /* If an individual transport is not set, get the transport for this router, if any. It might be expanded, or it might be unset if this router has verify_only set. */ if (!individual_transport_set) { if (!rf_get_transport(rblock->transport_name, &(rblock->transport), addr, rblock->name, NULL)) return DEFER; transport = rblock->transport; } /* Deal with the case of a local transport. The host list is passed over as a single text string that ends up in $host. */ if (transport != NULL && transport->info->local) { if (hostlist[0] != 0) { host_item *h; addr->host_list = h = store_get(sizeof(host_item)); h->name = string_copy(hostlist); h->address = NULL; h->port = PORT_NONE; h->mx = MX_NONE; h->status = hstatus_unknown; h->why = hwhy_unknown; h->last_try = 0; h->next = NULL; } /* There is nothing more to do other than to queue the address for the local transport, filling in any uid/gid. This can be done by the common rf_queue_add() function. */ addr->transport = transport; return rf_queue_add(addr, addr_local, addr_remote, rblock, pw)? OK : DEFER; } /* There is either no transport (verify_only) or a remote transport. A host list is mandatory in either case, except when verifying, in which case the address is just accepted. */ if (hostlist[0] == 0) { if (verify != v_none) goto ROUTED; addr->message = string_sprintf("error in %s router: no host(s) specified " "for domain %s", rblock->name, domain); log_write(0, LOG_MAIN, "%s", addr->message); return DEFER; } /* Otherwise we finish the routing here by building a chain of host items for the list of configured hosts, and then finding their addresses. */ host_build_hostlist(&(addr->host_list), hostlist, randomize); rc = rf_lookup_hostlist(rblock, addr, rblock->ignore_target_hosts, lookup_type, ob->hff_code, addr_new); if (rc != OK) return rc; /* If host_find_failed is set to "ignore", it is possible for all the hosts to be ignored, in which case we will end up with an empty host list. What happens is controlled by host_all_ignored. */ if (addr->host_list == NULL) { int i; DEBUG(D_route) debug_printf("host_find_failed ignored every host\n"); if (ob->hai_code == hff_decline) return DECLINE; if (ob->hai_code == hff_pass) return PASS; for (i = 0; i < hff_count; i++) if (ob->hai_code == hff_codes[i]) break; addr->message = string_sprintf("lookup failed for all hosts in %s router: " "host_find_failed=ignore host_all_ignored=%s", rblock->name, hff_names[i]); if (ob->hai_code == hff_defer) return DEFER; if (ob->hai_code == hff_fail) return FAIL; addr->special_action = SPECIAL_FREEZE; return DEFER; } /* Finally, since we have done all the routing here, there must be a transport defined for these hosts. It will be a remote one, as a local transport is dealt with above. However, we don't need one if verifying only. */ if (transport == NULL && verify == v_none) { log_write(0, LOG_MAIN, "Error in %s router: no transport defined", rblock->name); addr->message = US"error in router: transport missing"; return DEFER; } /* Fill in the transport, queue for remote delivery. The yield of rf_queue_add() is always TRUE for a remote transport. */ ROUTED: addr->transport = transport; (void)rf_queue_add(addr, addr_local, addr_remote, rblock, NULL); return OK; }
uschar *bmi_get_base64_verdict(uschar *bmi_local_part, uschar *bmi_domain) { BmiError err; BmiErrorLocation err_loc; BmiErrorType err_type; BmiVerdict *verdict = NULL; const BmiRecipient *recipient = NULL; const char *verdict_str = NULL; uschar *verdict_ptr; uschar *verdict_buffer = NULL; int sep = 0; /* return nothing if there are no verdicts available */ if (bmi_verdicts == NULL) return NULL; /* allocate room for the b64 verdict string */ verdict_buffer = store_get(Ustrlen(bmi_verdicts)+1); /* loop through verdicts */ verdict_ptr = bmi_verdicts; while ((verdict_str = (const char *)string_nextinlist(&verdict_ptr, &sep, verdict_buffer, Ustrlen(bmi_verdicts)+1)) != NULL) { /* create verdict from base64 string */ err = bmiCreateVerdictFromStr(verdict_str, &verdict); if (bmiErrorIsFatal(err) == BMI_TRUE) { err_loc = bmiErrorGetLocation(err); err_type = bmiErrorGetType(err); log_write(0, LOG_PANIC, "bmi error [loc %d type %d]: bmiCreateVerdictFromStr() failed. [%s]", (int)err_loc, (int)err_type, verdict_str); return NULL; }; /* loop through rcpts for this verdict */ for ( recipient = bmiVerdictAccessFirstRecipient(verdict); recipient != NULL; recipient = bmiVerdictAccessNextRecipient(verdict, recipient)) { uschar *rcpt_local_part; uschar *rcpt_domain; /* compare address against our subject */ rcpt_local_part = (unsigned char *)bmiRecipientAccessAddress(recipient); rcpt_domain = Ustrchr(rcpt_local_part,'@'); if (rcpt_domain == NULL) { rcpt_domain = US""; } else { *rcpt_domain = '\0'; rcpt_domain++; }; if ( (strcmpic(rcpt_local_part, bmi_local_part) == 0) && (strcmpic(rcpt_domain, bmi_domain) == 0) ) { /* found verdict */ bmiFreeVerdict(verdict); return (uschar *)verdict_str; }; }; bmiFreeVerdict(verdict); }; return NULL; }
void auth_cyrus_sasl_init(auth_instance *ablock) { auth_cyrus_sasl_options_block *ob = (auth_cyrus_sasl_options_block *)(ablock->options_block); const uschar *list, *listptr, *buffer; int rc, i; unsigned int len; uschar *rs_point, *expanded_hostname; char *realm_expanded; sasl_conn_t *conn; sasl_callback_t cbs[] = { {SASL_CB_GETOPT, NULL, NULL }, {SASL_CB_LIST_END, NULL, NULL}}; /* default the mechanism to our "public name" */ if (ob->server_mech == NULL) ob->server_mech = string_copy(ablock->public_name); expanded_hostname = expand_string(ob->server_hostname); if (expanded_hostname == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator: " "couldn't expand server_hostname [%s]: %s", ablock->name, ob->server_hostname, expand_string_message); realm_expanded = NULL; if (ob->server_realm != NULL) { realm_expanded = CS expand_string(ob->server_realm); if (realm_expanded == NULL) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator: " "couldn't expand server_realm [%s]: %s", ablock->name, ob->server_realm, expand_string_message); } /* we're going to initialise the library to check that there is an * authenticator of type whatever mechanism we're using */ cbs[0].proc = (int(*)(void)) &mysasl_config; cbs[0].context = ob->server_mech; if ((rc = sasl_server_init(cbs, "exim")) != SASL_OK ) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator: " "couldn't initialise Cyrus SASL library.", ablock->name); if ((rc = sasl_server_new(CS ob->server_service, CS expanded_hostname, realm_expanded, NULL, NULL, NULL, 0, &conn)) != SASL_OK ) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator: " "couldn't initialise Cyrus SASL server connection.", ablock->name); if ((rc = sasl_listmech(conn, NULL, "", ":", "", (const char **)&list, &len, &i)) != SASL_OK ) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator: " "couldn't get Cyrus SASL mechanism list.", ablock->name); i = ':'; listptr = list; HDEBUG(D_auth) { debug_printf("Initialised Cyrus SASL service=\"%s\" fqdn=\"%s\" realm=\"%s\"\n", ob->server_service, expanded_hostname, realm_expanded); debug_printf("Cyrus SASL knows mechanisms: %s\n", list); } /* the store_get / store_reset mechanism is hierarchical * the hierarchy is stored for us behind our back. This point * creates a hierarchy point for this function. */ rs_point = store_get(0); /* loop until either we get to the end of the list, or we match the * public name of this authenticator */ while ( ( buffer = string_nextinlist(&listptr, &i, NULL, 0) ) && strcmpic(buffer,ob->server_mech) ); if (!buffer) log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator: " "Cyrus SASL doesn't know about mechanism %s.", ablock->name, ob->server_mech); store_reset(rs_point); HDEBUG(D_auth) debug_printf("Cyrus SASL driver %s: %s initialised\n", ablock->name, ablock->public_name); /* make sure that if we get here then we're allowed to advertise. */ ablock->server = TRUE; sasl_dispose(&conn); sasl_done(); }
static int json_find(void *handle, uschar *filename, const uschar *keystring, int length, uschar **result, uschar **errmsg, uint *do_cache) { FILE * f = handle; json_t * j, * j0; json_error_t jerr; uschar * key; int sep = 0; length = length; /* Keep picky compilers happy */ do_cache = do_cache; /* Keep picky compilers happy */ rewind(f); if (!(j = json_loadf(f, 0, &jerr))) { *errmsg = string_sprintf("json error on open: %.*s\n", JSON_ERROR_TEXT_LENGTH, jerr.text); return FAIL; } j0 = j; for (int k = 1; (key = string_nextinlist(&keystring, &sep, NULL, 0)); k++) { BOOL numeric = TRUE; for (uschar * s = key; *s; s++) if (!isdigit(*s)) { numeric = FALSE; break; } if (!(j = numeric ? json_array_get(j, (size_t) strtoul(CS key, NULL, 10)) : json_object_get(j, CCS key) ) ) { DEBUG(D_lookup) debug_printf("%s, for key %d: '%s'\n", numeric ? US"bad index, or not json array" : US"no such key, or not json object", k, key); json_decref(j0); return FAIL; } } switch (json_typeof(j)) { case JSON_STRING: *result = string_copyn(CUS json_string_value(j), json_string_length(j)); break; case JSON_INTEGER: *result = string_sprintf("%" JSON_INTEGER_FORMAT, json_integer_value(j)); break; case JSON_REAL: *result = string_sprintf("%f", json_real_value(j)); break; case JSON_TRUE: *result = US"true"; break; case JSON_FALSE: *result = US"false"; break; case JSON_NULL: *result = NULL; break; default: *result = US json_dumps(j, 0); break; } json_decref(j0); return OK; }