How can I extract certain fields from a text file and output them on one line per record? - perl

I have the output from an nmap scan in a text file. Records are delimited by --. How can I extract certain fields and output them on a single line per record, with fields separated by a delimiter?
Here is a sample of the input file:
--
Nmap scan report for mail.mydomain.com (146.221.53.49)
Host is up (0.23s latency).
PORT STATE SERVICE
443/tcp open https
| ssl-cert: Subject: commonName=mail.mydomain.com/organizationName=The Company & Co. LLC/stateOrProvinceName=Paris/countryName=FR
| Issuer: commonName=DigiCert Secure Server CA/organizationName=DigiCert Inc/countryName=US
| Public Key type: rsa
| Public Key bits: 2048
| Not valid before: 2013-12-26T00:00:00+00:00
| Not valid after: 2015-01-21T12:00:00+00:00
| MD5: c528 4a28 4860 0a8c 112c 5f91 b63a 1d82
--
Nmap scan report for www.firstdomain.net (66.103.112.215)
Host is up (0.21s latency).
PORT STATE SERVICE
443/tcp open https
| ssl-cert: Subject: commonName=*.firstdomain.net/organizationName=FIRSTDOMAIN Ltd./stateOrProvinceName=Sofia/countryName=RO
| Issuer: commonName=GeoTrust SSL CA - G2/organizationName=GeoTrust Inc./countryName=US
| Public Key type: rsa
| Public Key bits: 2048
| Not valid before: 2014-09-28T23:00:00+00:00
| Not valid after: 2018-09-28T22:59:59+00:00
| MD5: ad44 e45f f677 14d9 bccf 8198 7002 457e
--
Nmap scan report for owa.second-domain.com.com.rs (156.113.124.14)
Host is up (0.21s latency).
PORT STATE SERVICE
443/tcp open https
| ssl-cert: Subject: commonName=owa.second-domain.com.com.rs/organizationName=Second Corporation LP/stateOrProvinceName=Malta/countryName=MT
| Issuer: commonName=VeriSign Class 3 Secure Server CA - G3/organizationName=VeriSign, Inc./countryName=US
| Public Key type: rsa
| Public Key bits: 2048
| Not valid before: 2013-09-04T23:00:00+00:00
| Not valid after: 2014-11-04T23:59:59+00:00
| MD5: 7c54 3427 bc82 f94d 4448 3d19 6700 4fbe
--
Expected output:
146.221.53.49; mail.mydomain.com; The Company & Co. LLC; Paris; FR; DigiCert Secure Server CA; 2013-12-26; 2015-01-21; c528 4a28 4860 0a8c 112c 5f91 b63a 1d82
66.103.112.215; =*.firstdomain.net; FIRSTDOMAIN Ltd.; Sofia; RO; 2014-09-28; 2018-09-28; ad44 e45f f677 14d9 bccf 8198 7002 457e

As has been said, it is very much frowned upon to simply post a requirement and wait for a kindly soul to do your work for you. But this isn't a very straightforward task, and I believe the Nmap::Parser module expects XML for input, so here is something to get you started.
use strict;
use warnings 'all';
use 5.010;
use autodie;
use constant REQUIRED_FIELDS => qw/
host
name
organizationName
stateOrProvinceName
countryName
issuerCommonName
startDate
endDate
MD5
/;
open my $fh, '<', 'nmap.nmap';
my (#data, %item);
while (<$fh>) {
if (/\A--$/) {
push #data, { %item } if %item;
%item = ();
}
elsif ( m{Issuer:} ) {
$item{'issuer'.ucfirst $1} = $2 while m{(\w+)=([^/]+)(?<=\S)}g;
}
elsif ( m{Not valid (before|after):\s*([\d-]+)} ) {
my $key = $1 eq 'before' ? 'startDate' : 'endDate';
$item{$key} = $2;
}
elsif ( m{\ANmap scan report for ([\w.-]+)\s+\(([\d.]+)\)} ) {
$item{name} = $1;
$item{host} = $2;
}
elsif (m{(MD5):\s*([a-z0-9\s]+(?<=\S))}) {
$item{MD5} = $2;
}
else {
$item{$1} = $2 while m{(\w+)=([^/]+)(?<=\S)}g;
}
}
push #data, { %item } if %item;
for my $item (#data) {
print join('; ', #{$item}{(REQUIRED_FIELDS)}), "\n";
}
output
146.221.53.49; mail.mydomain.com; The Company & Co. LLC; Paris; FR; DigiCert Secure Server CA; 2013-12-26; 2015-01-21; c528 4a28 4860 0a8c 112c 5f91 b63a 1d82
66.103.112.215; www.firstdomain.net; FIRSTDOMAIN Ltd.; Sofia; RO; GeoTrust SSL CA - G2; 2014-09-28; 2018-09-28; ad44 e45f f677 14d9 bccf 8198 7002 457e
156.113.124.14; owa.second-domain.com.com.rs; Second Corporation LP; Malta; MT; VeriSign Class 3 Secure Server CA - G3; 2013-09-04; 2014-11-04; 7c54 3427 bc82 f94d 4448 3d19 6700 4fbe

Related

Opensips 2.4 can't make outbound call

I followed tutorial on https://www.powerpbx.org/content/opensips-v24-debian-v8-mariadb-apache-v1
With minor tweaks for "Debian Buster" I have installed all components, services starts with no error, I created few subscribers from opensipscp, under alias I added DID number pointing username of sip device,
under routing added dr_gateway with type 1 and added ip address of DID provider trunk.
Inbound calls are fine.
Then I added IP's for my outbound trunks, set gateway type - 2
Added rules to include all outbound gateways for prefix starting 353
In dialplan I have added rule to translate from local format to E164, but it seem to not work
I can't get my head around how to succeed with outbound calls, I have spent whole weekend digging trough opensips documentation page and the book "Building Telephony Systems with OpenSIPS Second Edition" by Flavio-E.-Goncalves over and over again.
Here is debug output form opensips during call
DBG:dialplan:dp_translate_f: dpid is 10 partition is default
Dec 22 23:39:26 [892] DBG:dialplan:dp_get_svalue: searching 15
Dec 22 23:39:26 [892] DBG:dialplan:dp_translate_f: input is 0899000000
Dec 22 23:39:26 [892] DBG:dialplan:dp_translate_f: Checking with dpid 10
Dec 22 23:39:26 [892] DBG:dialplan:translate: No matching rule for input 0899000000
Dec 22 23:39:26 [892] DBG:dialplan:dp_translate_f: could not translate 0899000000 with dpid 10
Dec 22 23:39:26 [892] DBG:dialplan:dp_translate_f: dpid is 10 partition is default
Dec 22 23:39:26 [892] DBG:dialplan:dp_get_svalue: searching 15
Dec 22 23:39:26 [892] DBG:dialplan:dp_translate_f: input is 0899000000
Dec 22 23:39:26 [892] DBG:dialplan:dp_translate_f: Checking with dpid 10
Dec 22 23:39:26 [892] DBG:dialplan:translate: No matching rule for input 0899000000
Dec 22 23:39:26 [892] DBG:dialplan:dp_translate_f: could not translate 0899000000 with dpid 10
Dec 22 23:39:26 [892] DBG:registrar:parse_lookup_flags: final flags: 1
Dec 22 23:39:26 [892] DBG:registrar:lookup: '0899631338#example.ie' Not found in usrloc
Dialplan rule I am using is
MariaDB [opensips]> select * from dialplan;
+----+------+----+----------+----------------+-------------+-------------+-----------+---------+----------+----------------+
| id | dpid | pr | match_op | match_exp | match_flags | subst_exp | repl_exp | timerec | disabled | attrs |
+----+------+----+----------+----------------+-------------+-------------+-----------+---------+----------+----------------+
| 2 | 10 | 1 | 0 | ^089[0-9]{7}+$ | 0 | "^089(.+)$" | "35389\1" | NULL | 0 | IE Lyca Mobile |
+----+------+----+----------+----------------+-------------+-------------+-----------+---------+----------+----------------+
my gateway list
MariaDB [opensips]> select * from dr_gateways;
+----+------+------+-----------------+-------+------------+-------+------------+-------+--------+-------------+
| id | gwid | type | address | strip | pri_prefix | attrs | probe_mode | state | socket | description |
+----+------+------+-----------------+-------+------------+-------+------------+-------+--------+-------------+
| 1 | 1 | 1 | 1.1.1.1 | 0 | | | 0 | 0 | | inbound |
| 2 | 2 | 2 | 2.2.2.2 | 0 | | | 0 | 1 | | gw 1 |
| 3 | 3 | 2 | 3.3.3.3 | 0 | | | 0 | 0 | | gw 2 |
| 4 | 4 | 2 | 4.4.4.4 | 0 | | | 0 | 0 | | gw 3 |
| 5 | 5 | 2 | 5.5.5.5 | 0 | | | 0 | 0 | | gw 4 |
+----+------+------+-----------------+-------+------------+-------+------------+-------+--------+-------------+
Carriers
MariaDB [opensips]> select * from dr_carriers;
+----+-----------+---------+-------+-------+-------+-------------+
| id | carrierid | gwlist | flags | state | attrs | description |
+----+-----------+---------+-------+-------+-------+-------------+
| 1 | | 2,3,4,5 | 0 | 0 | | Provide |
+----+-----------+---------+-------+-------+-------+-------------+
DR Rules
MariaDB [opensips]> select * from dr_rules;
+--------+---------+--------+---------+----------+---------+---------+-------+-------------+
| ruleid | groupid | prefix | timerec | priority | routeid | gwlist | attrs | description |
+--------+---------+--------+---------+----------+---------+---------+-------+-------------+
| 1 | 0,1 | 353 | | 1 | | 2,3,4,5 | | IE |
+--------+---------+--------+---------+----------+---------+---------+-------+-------------+
1 row in set (0.001 sec)
my opensips.cfg file
#
# OpenSIPS residential configuration script
# by OpenSIPS Solutions <team#opensips-solutions.com>
#
# This script was generated via "make menuconfig", from
# the "Residential" scenario.
# You can enable / disable more features / functionalities by
# re-generating the scenario with different options.#
#
# Please refer to the Core CookBook at:
# http://www.opensips.org/Resources/DocsCookbooks
# for a explanation of possible statements, functions and parameters.
#
####### Global Parameters #########
log_level=3
log_stderror=no
log_facility=LOG_LOCAL0
children=4
/* uncomment the following lines to enable debugging */
debug_mode=yes
/* uncomment the next line to enable the auto temporary blacklisting of
not available destinations (default disabled) */
#disable_dns_blacklist=no
/* uncomment the next line to enable IPv6 lookup after IPv4 dns
lookup failures (default disabled) */
#dns_try_ipv6=yes
/* comment the next line to enable the auto discovery of local aliases
based on reverse DNS on IPs */
auto_aliases=no
listen=udp:123.123.123.123:5060 # CUSTOMIZE ME
listen=tcp:123.123.123.123:5060 # CUSTOMIZE ME
####### Modules Section ########
#set module path
mpath="/usr/lib/x86_64-linux-gnu/opensips/modules/"
#### SIGNALING module
loadmodule "signaling.so"
#### StateLess module
loadmodule "sl.so"
#### Transaction Module
loadmodule "tm.so"
modparam("tm", "fr_timeout", 5)
modparam("tm", "fr_inv_timeout", 30)
modparam("tm", "restart_fr_on_each_reply", 0)
modparam("tm", "onreply_avp_mode", 1)
#### Record Route Module
loadmodule "rr.so"
/* do not append from tag to the RR (no need for this script) */
modparam("rr", "append_fromtag", 0)
#### MAX ForWarD module
loadmodule "maxfwd.so"
#### SIP MSG OPerationS module
loadmodule "sipmsgops.so"
#### FIFO Management Interface
loadmodule "mi_fifo.so"
modparam("mi_fifo", "fifo_name", "/tmp/opensips_fifo")
modparam("mi_fifo", "fifo_mode", 0666)
#### URI module
loadmodule "uri.so"
modparam("uri", "use_uri_table", 0)
#### MYSQL module
loadmodule "db_mysql.so"
#### HTTPD module
loadmodule "httpd.so"
modparam("httpd", "port", 8888)
#### USeR LOCation module
loadmodule "usrloc.so"
modparam("usrloc", "nat_bflag", "NAT")
modparam("usrloc", "db_mode", 2)
modparam("usrloc", "db_url",
"mysql://opensips:secret#localhost/opensips") # CUSTOMIZE ME
#### REGISTRAR module
loadmodule "registrar.so"
modparam("registrar", "tcp_persistent_flag", "TCP_PERSISTENT")
modparam("registrar", "received_avp", "$avp(received_nh)")/* uncomment the next line not to allow more than 10 contacts per AOR */
#modparam("registrar", "max_contacts", 10)
#### ACCounting module
loadmodule "acc.so"
/* what special events should be accounted ? */
modparam("acc", "early_media", 0)
modparam("acc", "report_cancels", 0)
/* by default we do not adjust the direct of the sequential requests.
if you enable this parameter, be sure the enable "append_fromtag"
in "rr" module */
modparam("acc", "detect_direction", 0)
modparam("acc", "db_url",
"mysql://opensips:secret#localhost/opensips") # CUSTOMIZE ME
#### AUTHentication modules
loadmodule "auth.so"
loadmodule "auth_db.so"
modparam("auth_db", "calculate_ha1", yes)
modparam("auth_db", "password_column", "password")
modparam("auth_db|uri", "db_url",
"mysql://opensips:secret#localhost/opensips") # CUSTOMIZE ME
modparam("auth_db", "load_credentials", "")
#### ALIAS module
loadmodule "alias_db.so"
modparam("alias_db", "db_url",
"mysql://opensips:secret#localhost/opensips") # CUSTOMIZE ME
#### DOMAIN module
loadmodule "domain.so"
modparam("domain", "db_url",
"mysql://opensips:secret#localhost/opensips") # CUSTOMIZE ME
modparam("domain", "db_mode", 1) # Use caching
modparam("auth_db|usrloc|uri", "use_domain", 1)
#### PRESENCE modules
loadmodule "xcap.so"
loadmodule "presence.so"
loadmodule "presence_xml.so"
modparam("xcap|presence", "db_url",
"mysql://opensips:secret#localhost/opensips") # CUSTOMIZE ME
modparam("presence_xml", "force_active", 1)
modparam("presence", "fallback2db", 0)
#### DIALOG module
loadmodule "dialog.so"
modparam("dialog", "dlg_match_mode", 1)
modparam("dialog", "default_timeout", 21600) # 6 hours timeout
modparam("dialog", "db_mode", 2)
modparam("dialog", "db_url",
"mysql://opensips:secret#localhost/opensips") # CUSTOMIZE ME
#### NAT modules
loadmodule "nathelper.so"
modparam("nathelper", "natping_interval", 10)
modparam("nathelper", "ping_nated_only", 1)
modparam("nathelper", "sipping_bflag", "SIP_PING_FLAG")
modparam("nathelper", "sipping_from", "sip:pinger#127.0.0.1") #CUSTOMIZE ME
modparam("nathelper", "received_avp", "$avp(received_nh)")
loadmodule "rtpengine.so"
modparam("rtpengine", "rtpengine_sock", "udp:localhost:2223") # CUSTOMIZE ME
#### DIALPLAN module
loadmodule "dialplan.so"
modparam("dialplan", "db_url",
"mysql://opensips:secret#localhost/opensips") # CUSTOMIZE ME
#### DYNAMMIC ROUTING module
loadmodule "drouting.so"
modparam("drouting", "db_url",
"mysql://opensips:secret#localhost/opensips") # CUSTOMIZE ME
#### MI_HTTP module
loadmodule "mi_http.so"
loadmodule "mi_json.so"
loadmodule "proto_udp.so"
loadmodule "proto_tcp.so"
####### Routing Logic ########
# main request routing logic
route{
# initial NAT handling; detect if the request comes from behind a NAT
# and apply contact fixing
force_rport();
if (nat_uac_test("23")) {
if (is_method("REGISTER")) {
fix_nated_register();
setbflag(NAT);
} else {
fix_nated_contact();
setflag(NAT);
}
}
if (!mf_process_maxfwd_header("10")) {
send_reply("483","Too Many Hops");
exit;
}
if (has_totag()) {
# handle hop-by-hop ACK (no routing required)
if ( is_method("ACK") && t_check_trans() ) {
t_relay();
exit;
}
# sequential request within a dialog should
# take the path determined by record-routing
if ( !loose_route() ) {
if (is_method("SUBSCRIBE") && is_myself("$rd")) {
# in-dialog subscribe requests
route(handle_presence);
exit;
}
# we do record-routing for all our traffic, so we should not
# receive any sequential requests without Route hdr.
send_reply("404","Not here");
exit;
}
# validate the sequential request against dialog
if ( $DLG_status!=NULL && !validate_dialog() ) {
xlog("In-Dialog $rm from $si (callid=$ci) is not valid according to dialog\n");
## exit;
}
if (is_method("BYE")) {
# do accounting even if the transaction fails
do_accounting("db","failed");
}
if (check_route_param("nat=yes"))
setflag(NAT);
# route it out to whatever destination was set by loose_route()
# in $du (destination URI).
route(relay);
exit;
}
# CANCEL processing
if (is_method("CANCEL")) {
if (t_check_trans())
t_relay();
exit;
}
# absorb retransmissions, but do not create transaction
t_check_trans();
if ( !(is_method("REGISTER") || is_from_gw() ) ) {
if (is_from_local()) {
# authenticate if from local subscriber
# authenticate all initial non-REGISTER request that pretend to be
# generated by local subscriber (domain from FROM URI is local)
if (!proxy_authorize("", "subscriber")) {
proxy_challenge("", "0");
exit;
}
if (!db_check_from()) {
send_reply("403","Forbidden auth ID");
exit;
}
consume_credentials();
# caller authenticated
} else {
# if caller is not local, then called number must be local
if (!is_uri_host_local()) {
send_reply("403","Relay Forbidden");
exit;
}
}
}
# preloaded route checking
if (loose_route()) {
xlog("L_ERR",
"Attempt to route with preloaded Route's [$fu/$tu/$ru/$ci]");
if (!is_method("ACK"))
send_reply("403","Preload Route denied");
exit;
}
# record routing
if (!is_method("REGISTER|MESSAGE"))
record_route();
# account only INVITEs
if (is_method("INVITE")) {
# create dialog with timeout
if ( !create_dialog("B") ) {
send_reply("500","Internal Server Error");
exit;
}
do_accounting("db");
}
if (!is_uri_host_local()) {
append_hf("P-hint: outbound\r\n");
route(relay);
}
# requests for my domain
if( is_method("PUBLISH|SUBSCRIBE"))
route(handle_presence);
if (is_method("REGISTER")) {
# authenticate the REGISTER requests
if (!www_authorize("", "subscriber")) {
www_challenge("", "0");
exit;
}
if (!db_check_to()) {
send_reply("403","Forbidden auth ID");
exit;
}
if ($proto == "tcp")
setflag(TCP_PERSISTENT);
if (isflagset(NAT)) {
setbflag(SIP_PING_FLAG);
}
if (!save("location"))
sl_reply_error();
exit;
}
if ($rU==NULL) {
# request with no Username in RURI
send_reply("484","Address Incomplete");
exit;
}
# apply DB based aliases
alias_db_lookup("dbaliases");
**# apply transformations from dialplan table
dp_translate("10","$rU/$rU");
if (dp_translate("10","$rU/$rU") ) {
if (!do_routing("0")) {
send_reply("500","No PSTN Route found");
exit;
}
route(relay);
exit;
}**
# do lookup with method filtering
if (!lookup("location","m")) {
if (!db_does_uri_exist()) {
send_reply("420","Bad Extension");
exit;
}
# redirect to a different VM system
$du = "sip:127.0.0.2:5060"; # CUSTOMIZE ME
route(relay);
}
if (isbflagset(NAT)) setflag(NAT);
# when routing via usrloc, log the missed calls also
do_accounting("db","missed");
route(relay);
}
route[relay] {
# for INVITEs enable some additional helper routes
if (is_method("INVITE")) {
if (isflagset(NAT)) {
rtpengine_offer("ro");
}
t_on_branch("per_branch_ops");
t_on_reply("handle_nat");
t_on_failure("missed_call");
}
if (isflagset(NAT)) {
add_rr_param(";nat=yes");
}
if (!t_relay()) {
send_reply("500","Internal Error");
}
exit;
}
# Presence route
route[handle_presence]
{
if (!t_newtran()) {
sl_reply_error();
exit;
}
if(is_method("PUBLISH")) {
handle_publish();
} else
if( is_method("SUBSCRIBE")) {
handle_subscribe();
}
exit;
}
branch_route[per_branch_ops] {
xlog("new branch at $ru\n");
}
onreply_route[handle_nat] {
if (nat_uac_test("1"))
fix_nated_contact();
if ( isflagset(NAT) )
rtpengine_answer("ro");
xlog("incoming reply\n");
}
failure_route[missed_call] {
if (t_was_cancelled()) {
exit;
}
# uncomment the following lines if you want to block client
# redirect based on 3xx replies.
##if (t_check_status("3[0-9][0-9]")) {
##t_reply("404","Not found");
## exit;
##}
# redirect the failed to a different VM system
if (t_check_status("486|408")) {
$du = "sip:127.0.0.2:5060"; # CUSTOMIZE ME
# do not set the missed call flag again
route(relay);
}
}
local_route {
if (is_method("BYE") && $DLG_dir=="UPSTREAM") {
acc_db_request("200 Dialog Timeout", "acc");
}
}
In the dialplan table, you have added extra quotes around the dialplan.subst_exp and dialplan.repl_exp values. Instead of "^089(.+)$" and "35389\1", try to provision ^089(.+)$ and 35389\1. Another mistake is that you are using match_op == 0 (string match) instead of match_op == 1 (regex match). Please read the dialplan documentation carefully before provisioning data into any of the columns.
The drouting part looks good. It should properly route out the 353 prefix.

How to code in powershell a check if there are unread mails on an imap account?

It seem that I worded my question unclear here the reworded version:
How to code in powershell a script which checks on an third party imap account if there are unread mails.
The account in mind uses TSL with user/pwd authorization.
IMAP is not a complex protocol, it's line-based and the number of relevant commands is limited, especially if you want nothing more than to check for unread mails in the inbox.
So it's pretty straightforward to build an IMAP client on top of System.Net.Sockets.TcpClient. SSL/TLS is bit of a complication, but not too bad.
The conversation with an IMAP server goes like this:
Client: A001 command argument argument
Server: * response line 1
* response line 2
A001 OK response line 3
Where A001 is the command tag, which is supposed to identify commands. Often it's in the form of a incrementing counter (a1, a2, a3, ...) but really it can be anything. The server repeats the command tag in the final line of its response.
A sample conversation with a GMail IMAP server (authentication failed, obviously):
* OK Gimap ready for requests from 213.61.242.253 g189mb36880374lfe
a1 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIENTTOKEN AUTH=OAUTHBEARER AUTH=XOAUTH
a1 OK Thats all she wrote! g189mb36880374lfe
a2 LOGIN test test
a2 NO [AUTHENTICATIONFAILED] Invalid credentials (Failure)
a3 LOGOUT
* BYE Logout Requested g189mb36880374lfe
a3 OK Quoth the raven, nevermore... g189mb36880374lfe
The Powershell code that did this is not too complex:
using namespace System.IO;
using namespace System.Text;
using namespace System.Net.Sockets;
using namespace System.Net.Security;
using namespace System.Security.Cryptography.X509Certificates;
Set-StrictMode -Version 2.0
$DebugPreference = "Continue" # set to "SilentlyContinue" to hide Write-Debug output
$CRLF = "`r`n"
$server = "imap.gmail.com"
$port = 993
$username = "test"
$password = "test"
# connect to server
$client = [TcpClient]::new($server, $port)
$client.ReceiveTimeout = 2000 #milliseconds
# set up SSL stream, be lenient about the server's certificate
$acceptAnyCertificate = [RemoteCertificateValidationCallback] { $true }
$sslStream = [SslStream]::new($client.GetStream(), $false, $acceptAnyCertificate)
$sslStream.AuthenticateAsClient($server)
function StreamWrite {
param([Stream]$stream, [string]$command, [Encoding]$enc = [Encoding]::ASCII)
$data = $enc.GetBytes($command)
Write-Debug "> $($command.trim())"
$stream.Write($data, 0, $data.Length)
}
function StreamRead {
param([Stream]$stream, [int]$bufsize = 4*1KB, [Encoding]$enc = [Encoding]::ASCII)
$buffer = [byte[]]::new($bufsize)
$bytecount = $stream.Read($buffer, 0, $bufsize)
$response = $enc.GetString($buffer, 0, $bytecount)
Write-Debug "< $($response.trim())"
$response
}
# read server hello
$response = StreamRead $sslStream
StreamWrite $sslStream ("a1 CAPABILITY" + $CRLF)
$response = StreamRead $sslStream
# log in
StreamWrite $sslStream ("a2 LOGIN $username $password" + $CRLF)
$response = StreamRead $sslStream
# send mailbox commands...
# log out
StreamWrite $sslStream ("a3 LOGOUT" + $CRLF)
$response = StreamRead $sslStream
$sslStream.Close()
$client.Close()
Your mailbox command would probably be a simple select inbox, to which the server responds with a bunch of info, including the number of unseen emails (an example can be seen on the Wikipedia):
C: a002 select inbox
S: * 18 EXISTS
S: * FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
S: * 2 RECENT
S: * OK [UNSEEN 17] Message 17 is the first unseen message
S: * OK [UIDVALIDITY 3857529045] UIDs valid
S: a002 OK [READ-WRITE] SELECT completed
You'll probably need to experiment a little with your mail server, but it should be easy to figure out the necessary details.
Read Connecting to smtp.live.com with the TcpClient class to get an idea how to do STARTTLS instead of SSL, if that's what your server requires.

DNS BIND zone transfer error: "failed to connect: host unreachable"

I am setting up two local authoritative BIND DNS servers so that a client may communicate with virtual hosts on an apache server. One is the master (10.2.56.209) the other is the slave (10.2.56.186). I have the servers configured and they start, but I get this error in the log file on the slave when it tries to do the zone transfer from the master.
transfer of '2.10.in-addr.arpa/IN' from 10.2.56.209#53: failed to connect: host unreachable
transfer of '2.10.in-addr.arpa/IN' from 10.2.56.209#53: Transfer completed: 0 messages, 0 records, 0 bytes, 0.002 secs (0 bytes/sec)
Slave's named.conf file
options {
listen-on port 53 { 127.0.0.1; };
listen-on-v6 port 53 { ::1; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
allow-query { any; };
recursion no;
allow-transfer { none; };
dnssec-enable yes;
dnssec-validation yes;
/* Path to ISC DLV key */
bindkeys-file "/etc/named.iscdlv.key";
managed-keys-directory "/var/named/dynamic";
pid-file "/run/named/named.pid";
session-keyfile "/run/named/session.key";
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
};
zone "." IN {
type hint;
file "named.ca";
};
include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";
zone "cit.nku.edu" IN {
type slave;
file "cit.nku.edu";
masters{10.2.56.209; };
};
zone "2.10.in-addr.arpa" IN {
type slave;
file "2.10.in-addr.arpa";
masters{10.2.56.209; };
};
Master's named.conf file
options {
listen-on port 53 { 10.2.56.209; };
listen-on-v6 port 53 { ::1; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
allow-query { any; };
recursion no;
allow-transfer { none; };
dnssec-enable yes;
dnssec-validation yes;
/* Path to ISC DLV key */
bindkeys-file "/etc/named.iscdlv.key";
managed-keys-directory "/var/named/dynamic";
pid-file "/run/named/named.pid";
session-keyfile "/run/named/session.key";
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
};
zone "." IN {
type hint;
file "named.ca";
};
include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";
zone "cit.nku.edu" IN {
type master;
file "cit.nku.edu";
allow-transfer { 10.2.56.186; };
notify yes;
};
# reverse zone
zone "2.10.in-addr.arpa" IN {
type master;
file "2.10.in-addr.arpa";
allow-transfer {localhost; 10.2.56.186;};
notify yes;
};
forward zone file on the master
$TTL 1H
# IN SOA ns1.cit.nku.edu. root.cit.nku.edu (
10 ; serial
1H ; refresh
15M ; retry
4W ; expire
1H ; Negative caching TTL of 1 hour
)
; Name servers
cit.nku.edu. IN NS ns1.cit.nku.edu.
cit.nku.edu. IN NS ns2.cit.nku.edu.
ns1 IN A 10.2.56.209
ns2 IN A 10.2.56.186
# IN A 10.2.62.33
www IN A 10.2.62.33
reverse zone file
$TTL 86400
$ORIGIN 2.10.IN-ADDR.ARPA.
# IN SOA ns1.cit.nku.edu. root.cit.nku.edu. (
10 ;Serial
3600 ;refresh
1800 ;retry
604800 ;expire
86400 ;minimum ttl
)
; Name Servers
IN NS ns1.cit.nku.edu.
IN NS ns2.cit.nku.edu.
IN PTR cit.nku.edu.
209.56 IN PTR ns1.cit.nku.edu.
186.56 IN PTR ns2.cit.nku.edu.
33.62 IN PTR www.cit.nku.edu.
I can ping them between each other and dig the host names (ns1, ns2), but I cannot dig the ip addresses themselves. I have added the corresponding entries in the /etc/hosts and /etc/hostname files. I can provide other documents if needed. Any help is appreciated.

Private only dovecot, local docker configuration for one user fails login for Apple Mail

I'm trying to make a local docker-dovecot machine to archive my e-mails. I would like to query them with Apple Mail. I have a simple ubuntu docker machine (on an VM with parallels, because I'm on a Mac).
I have this local.conf:
# A comma separated list of IPs or hosts where to listen in for connections.
# "*" listens in all IPv4 interfaces, "::" listens in all IPv6 interfaces.
# If you want to specify non-default ports or anything more complex,
# edit conf.d/master.conf.
listen = *,::
# Protocols we want to be serving.
protocols = imap
# Static passdb.
# This can be used for situations where Dovecot doesn't need to verify the
# username or the password, or if there is a single password for all users:
passdb {
driver = static
args = password=dovecot
}
# Location for users' mailboxes. The default is empty, which means that Dovecot
# tries to find the mailboxes automatically. This won't work if the user
# doesn't yet have any mail, so you should explicitly tell Dovecot the full
# location.
#
# If you're using mbox, giving a path to the INBOX file (eg. /var/mail/%u)
# isn't enough. You'll also need to tell Dovecot where the other mailboxes are
# kept. This is called the "root mail directory", and it must be the first
# path given in the mail_location setting.
#
# There are a few special variables you can use, eg.:
#
# %u - username
# %n - user part in user#domain, same as %u if there's no domain
# %d - domain part in user#domain, empty if there's no domain
# %h - home directory
#
# See doc/wiki/Variables.txt for full list. Some examples:
#
# mail_location = maildir:~/Maildir
# mail_location = mbox:~/mail:INBOX=/var/mail/%u
# mail_location = mbox:/var/mail/%d/%1n/%n:INDEX=/var/indexes/%d/%1n/%n
#
# <doc/wiki/MailLocation.txt>
#
mail_location = maildir:/var/mail/%n
# System user and group used to access mails. If you use multiple, userdb
# can override these by returning uid or gid fields. You can use either numbers
# or names. <doc/wiki/UserIds.txt>
# mail_uid = CHANGE_THIS_to_your_short_user_name_or_uid
# mail_gid = admin
# SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt>
ssl = no
# Login user is internally used by login processes. This is the most untrusted
# user in Dovecot system. It shouldn't have access to anything at all.
# default_login_user = _dovenull
# Internal user is used by unprivileged processes. It should be separate from
# login user, so that login processes can't disturb other processes.
# default_internal_user = _dovecot
# Setting limits.
default_process_limit = 10
default_client_limit = 50
and I'm getting this from Apple Mail
May 23 07:15:58 Mail[87524] <Debug>: <0x7fe16f021cd0:[Non-authenticated]> Wrote: 1.11 ID ("name" "Mac OS X Mail" "version" "9.3 (3124)" "os" "Mac OS X" "os-version" "10.11.5 (15F34)" "vendor" "Apple Inc.")
May 23 07:15:58 Mail[87524] <Debug>: <0x7fe16f021cd0:[Non-authenticated]> Read: * ID {
name = Dovecot;
}
May 23 07:15:58 Mail[87524] <Debug>: <0x7fe16f021cd0:[Non-authenticated]> Read: 1.11 OK
May 23 07:15:58 Mail[87524] <Debug>: <0x7fe16f021cd0:[Non-authenticated]> Wrote: 3.11 LOGOUT
May 23 07:16:00 Mail[87524] <Debug>: <0x7fe16aa14590:[Disconnected]> Read: * OK [CAPABILITY (
IMAP4REV1,
"LITERAL+",
"SASL-IR",
"LOGIN-REFERRALS",
ID,
ENABLE,
IDLE,
"AUTH=PLAIN",
"AUTH=LOGIN"
)]
May 23 07:16:00 Mail[87524] <Debug>: <0x7fe16aa14590:[Non-authenticated]> Wrote: 1.23 ID ("name" "Mac OS X Mail" "version" "9.3 (3124)" "os" "Mac OS X" "os-version" "10.11.5 (15F34)" "vendor" "Apple Inc.")
May 23 07:16:00 Mail[87524] <Debug>: <0x7fe16aa14590:[Non-authenticated]> Read: * ID {
name = Dovecot;
}
May 23 07:16:00 Mail[87524] <Debug>: <0x7fe16aa14590:[Non-authenticated]> Read: 1.23 OK
May 23 07:16:00 Mail[87524] <Debug>: <0x7fe16aa14590:[Non-authenticated]> Wrote: 3.23 LOGOUT
and this from dovecot (mail.log):
May 23 05:07:22 f8ab3e20742f dovecot: master: Dovecot v2.2.9 starting up (core dumps disabled)
May 23 05:07:22 f8ab3e20742f dovecot: ssl-params: Generating SSL parameters
May 23 05:07:29 f8ab3e20742f dovecot: ssl-params: SSL parameters regeneration completed
May 23 05:07:52 f8ab3e20742f dovecot: imap-login: Aborted login (no auth attempts in 0 secs): user=<>, rip=10.211.55.2, lip=172.17.0.2, session=<IJwtbHszbgAK0zcC>
May 23 05:07:54 f8ab3e20742f dovecot: imap-login: Aborted login (no auth attempts in 0 secs): user=<>, rip=10.211.55.2, lip=172.17.0.2, session=<qsRNbHszdgAK0zcC>
The output of doveconf -n is (so "disable_plaintext_auth = no" is active):
# 2.2.9: /etc/dovecot/dovecot.conf
# OS: Linux 4.4.8-boot2docker x86_64 Ubuntu 14.04.4 LTS aufs
auth_mechanisms = plain login
default_client_limit = 50
default_process_limit = 10
disable_plaintext_auth = no
listen = *,::
mail_location = maildir:/var/mail/%n
namespace inbox {
inbox = yes
location =
mailbox Drafts {
special_use = \Drafts
}
mailbox Junk {
special_use = \Junk
}
mailbox Sent {
special_use = \Sent
}
mailbox "Sent Messages" {
special_use = \Sent
}
mailbox Trash {
special_use = \Trash
}
prefix =
}
passdb {
args = password=dovecot
driver = static
}
protocols = imap
ssl = no
Any suggestions why this login isn't working?
Thanks!
The solution is to fix and configure the following line correctly (from local.conf):
# mail_uid = CHANGE_THIS_to_your_short_user_name_or_uid
How did I find out? Thanks to #Kondybas for the pointer to try another client. I used Thunderbird and it produced dovecot log entries (why didn't Apple Mail produce these lines? No clue), saying that it couldn't switch to mail_uid user context. I extended dovecot Dockerfile and switched the user appropriately. Afterwards it worked with Thunderbird and then with Apple Mail.

Is there a limit in the number of processes that can be forked in perl?

I am facing a weird problem. The forked processes is not increasing more than 64.
sub create_process()
{
my $child_pid;
my #nsitr;
my $i = 0;
foreach my $domain (#domains)
{
#nsitr = #nameservers;
open my $dnsfh, '>', $outputfile or die "Unable to open $outputfile - $!";
foreach my $ns (#nameservers)
{
print "Forking child $i\n";
defined($child_pid = fork() ) or (die "Unable to fork a new process" && next);
$i++;
if($child_pid == 0)
{
&resolve_dns($dnsfh, $domain, $ns);
exit;
}
}
close $dnsfh;
}
}
Output
...
...
Forking child 60
Forking child 61
Forking child 62
Forking child 63
Forking child 64
Forking child 64
Forking child 64
Forking child 64
Forking child 64
...
...
Perl doesn't define such a limit, but most operating systems do. Use waitpid to reap children, or on Unix-like systems you can use sigaction (from the POSIX module) to ignore SIGCHLD with the SA_NOCLDWAIT flag to have the system reap children automatically. (Linux happens to let you omit SA_NOCLDWAIT, but you should use it anyway.)
If you want to do parallel lookups, you can either use the demo script included with Net::DNS or check out AnyEvent::DNS.
The latter provides
This module offers both a number of DNS convenience functions as well as a fully asynchronous and high-performance pure-perl stub resolver.
I haven't used it, but IO::Lambda::DNS would also allow parallel queries to be made:
# parallel async queries
lambda {
for my $site ( map { "www.$_.com" } qw(google yahoo perl)) {
context $site, 'MX', timeout => 0.25;
dns { print shift-> string if ref($_[0]) }
}
}-> wait;
Using those modules might be preferable to managing forks by hand.
Based on your comment, I think you might have misunderstood what I was trying to say. Maybe this will help:
#!/usr/bin/env perl
use strict; use warnings;
use AnyEvent::DNS;
use AnyEvent::Socket;
use YAML;
my %nameservers = (
'Google' => '8.8.4.4',
'Dnsadvantage' => '156.154.71.1',
'OpenDNS' => '208.67.222.222',
'Norton' => '198.153.194.1',
'Verizon' => '4.2.2.4',
'ScrubIt' => '207.225.209.66',
);
for my $ip ( values %nameservers ) {
$ip = AnyEvent::DNS->new(
server => [ parse_address($_) ],
timeout => [3],
);
}
my #domains = qw(example.com cnn.com bing.com);
my $cv = AnyEvent->condvar;
for my $domain (#domains) {
for my $ns (keys %nameservers) {
$cv->begin;
$nameservers{$ns}->resolve(
$domain, 'a', sub {
$cv->end;
print Dump { $ns => [ #{$_[0]}[0,4] ] };
}
);
}
}
$cv->recv;
Output:
---
ScrubIt:
- example.com
- 192.0.43.10
---
ScrubIt:
- cnn.com
- 157.166.226.26
---
Norton:
- example.com
- 192.0.43.10
---
OpenDNS:
- example.com
- 192.0.43.10
---
Dnsadvantage:
- example.com
- 192.0.43.10
---
Verizon:
- example.com
- 192.0.43.10
---
Google:
- example.com
- 192.0.43.10
---
ScrubIt:
- bing.com
- 65.52.107.149
---
Norton:
- cnn.com
- 157.166.255.18
---
OpenDNS:
- cnn.com
- 157.166.255.19
---
Dnsadvantage:
- cnn.com
- 157.166.226.25
---
Verizon:
- cnn.com
- 157.166.226.26
---
Google:
- cnn.com
- 157.166.255.18
---
Norton:
- bing.com
- 65.52.107.149
---
OpenDNS:
- bing.com
- 65.52.107.149
---
Dnsadvantage:
- bing.com
- 65.52.107.149
---
Verizon:
- bing.com
- 65.52.107.149
---
Google:
- bing.com
- 65.52.107.149
If you're on some kind of Unix system, you may want to use threads module instead of forks. Actually it is even heavier in some aspects and may require some extra housekeeping, but this could allow your to surpass forked process limit. There could be other limits that'd prevent you from creating big amount of threads though.