How to read from socket without blocking - asynchronous

I ran into a problem when dealing with the server, sending me initial "greetings header" (smtp server):
I need to read this header before send any commands and receive any answers from the server, but i dont know, how to do this, because Julia seems to lack any possibility to readi from IO stream without blocking: "read" command and its analogues does not have any NB-options, nb_available always is 0 though i know exactly that server send me header and my read buffer cant be empty (and "read" command issued right after "nb_available" give me data immediately, without blocking).
julia> s=connect("smtp.mail.ru",25)
TCPSocket(RawFD(18) open, 0 bytes waiting)
julia> nb_available(s)
0
julia> nb_available(s)
0
(after 5 seconds or so...)
julia> nb_available(s)
0
julia> t=read(s,10)
10-element Array{UInt8,1}:
0x32
0x32
0x30
0x20
0x73
0x6d
0x74
0x70
0x31
0x34
(HOW, WHY???? nb_available==0, but read returns me 10 bytes?!)
... (read was repeated many times...)
julia> t=read(s,10)
^CERROR: InterruptException:
Stacktrace:
[1] process_events at ./libuv.jl:82 [inlined]
[2] wait() at ./event.jl:216
[3] wait(::Condition) at ./event.jl:27
[4] wait_readnb(::TCPSocket, ::Int64) at ./stream.jl:296
[5] readbytes!(::TCPSocket, ::Array{UInt8,1}, ::Int64) at ./stream.jl:714
[6] read(::TCPSocket, ::Int64) at ./io.jl:529
I dont want to use #async for the simplest case described above.
Who knows, how to read from TCP socket in non-blocking mode, when i can determine some way, whether read buffer contain any data or no and/or whether next read issued by tcp client will block overall client process or no.
Is it possible in Julia without "green threads" usage?

Since no-one's provided an "official" solution yet, here's the workaround I mentioned above.
Functions:
# Causes stagnant 'nb' count to be updated.
# Note asynchronous nature; this means refresh may not yet have occurred
# when function has exited.
function refreshBufsize(s)
#async eof(s);
return nothing;
end;
# Check if socket is blocked (refresh bytecount first)
# Note, since refresh is asynchronous, may misreport 'blockage' until
# 'refresh' operation is actually finished; however, if socket is actually
# unblocked, subsequent calls of this function will eventually properly
# report socket is not blocked, and in general, misreporting blockage once
# or twice when socket is actually free is probably acceptable (rather
# than other way round).
function isblocked(s)
refreshBufsize(s)
return nb_available(s) == 0;
end;
# Peek contents of socket without consuming stream
function peek(s, nb)
refreshBufsize(s)
s.buffer.seekable = true;
Out = read(s.buffer, nb);
seekstart(s.buffer);
s.buffer.seekable = false
return Out
end;
Example: (console outputs denoted as "#>" comments, for copy-pastable code)
server = listen(9001);
sOut = connect(9001);
sIn = accept(server);
nb_available(sIn)
#> 0
isblocked(sIn)
#> true
refreshBufsize(sIn); # we expect no change, as we haven't written anything yet
isblocked(sIn)
#> true
write(sOut, "Greetinks and salutations!\n")
#> 27
write(sOut, "We would be honoured if you would join us.\n")
#> 43
refreshBufsize(sIn);
isblocked(sIn) # note: may say true at first (until refresh properly finished)
#> false
nb_available(sIn)
#> 27
String( peek( sIn, 10)) # peek socket contents without consuming
#> "Greetinks "
String( read( sIn, nb_available( sIn))) # read (consume) as normal
#> "Greetinks and salutations!\n"
nb_available(sIn) # note 0 even though second buffer awaiting. needs refresh!
#> 0
isblocked(sIn) # note: called "refresh" under the hood
# (but keep async in mind, i.e. might say 'true' at first!)
#> false
nb_available(sIn)
#> 43
String( read( sIn, nb_available( sIn)))
#> "We would be honoured if you would join us.\n"
isblocked(sIn)
#> true
EDIT: for comparison, a more typical "asynchronous" socket session (which typically relies on such "blocking" behaviour) would probably look something like this:
server = listen(9002);
sOut = connect(9002);
sIn = accept(server);
TaskRef = #async try
while true
In = String(readavailable(sIn));
if !isempty(In); println("Received from server: $In"); else; break; end
end
println("Connection closed normally");
catch E
println("Connection closed (with status $E)");
end;
write(sOut, "Stop repeating everything I say!\n");
#> Received from server: Stop repeating everything I say!
close(sIn)
#> Connection closed normally

Related

Sorry i'm stuck with freeraduis to LDAP

Ok Im a little stuck with FreeRad A little lost
I think I have found the problem, I just don't understand why
so If I try to auth over the wifi to rad it looks like its not getting the password below is the debug of that
Ready to process requests
(0) Received Access-Request Id 149 from 192.168.200.238:49881 to 192.168.20.2:1812 length 227
(0) User-Name = "testing"
(0) NAS-IP-Address = 192.168.200.238
(0) NAS-Identifier = "d221f94b63df"
(0) Called-Station-Id = "D2-21-F9-4B-63-DF:test no join"
(0) NAS-Port-Type = Wireless-802.11
(0) Service-Type = Framed-User
(0) Calling-Station-Id = "D2-5A-22-F3-F6-A1"
(0) Connect-Info = "CONNECT 0Mbps 802.11a"
(0) Acct-Session-Id = "08DE2818B2804F38"
(0) Acct-Multi-Session-Id = "47EF77EBC7B5BF7A"
(0) WLAN-Pairwise-Cipher = 1027076
(0) WLAN-Group-Cipher = 1027076
(0) WLAN-AKM-Suite = 1027073
(0) Framed-MTU = 1400
(0) EAP-Message = 0x02bd000c0174657374696e67
(0) Message-Authenticator = 0xcef6985af177d3099edb44dbcfaba6e7
(0) # Executing section authorize from file /etc/freeradius/3.0/sites-enabled/my_server
(0) authorize {
rlm_ldap (ldap): Reserved connection (0)
(0) ldap: EXPAND (cn=%{%{Stripped-User-Name}:-%{User-Name}})
(0) ldap: --> (cn=testing)
(0) ldap: Performing search in "ou=users,dc=ldap,DC=alexosaurous,DC=co,DC=nz" with filter "(cn=testing)", scope "sub"
(0) ldap: Waiting for search result...
(0) ldap: User object found at DN "cn=testing,ou=users,dc=ldap,dc=alexosaurous,dc=co,dc=nz"
(0) ldap: Processing user attributes
(0) ldap: WARNING: No "known good" password added. Ensure the admin user has permission to read the password attribute
(0) ldap: WARNING: PAP authentication will *NOT* work with Active Directory (if that is what you were trying to configure)
rlm_ldap (ldap): Released connection (0)
(0) [ldap] = ok
(0) if ((ok || updated) && User-Password) {
(0) if ((ok || updated) && User-Password) -> FALSE
(0) } # authorize = ok
(0) ERROR: No Auth-Type found: rejecting the user via Post-Auth-Type = Reject
(0) Failed to authenticate the user
(0) Using Post-Auth-Type Reject
(0) Post-Auth-Type sub-section not found. Ignoring.
(0) Delaying response for 1.000000 seconds
Waking up in 0.3 seconds.
Waking up in 0.6 seconds.
(0) Sending delayed response
(0) Sent Access-Reject Id 149 from 192.168.20.2:1812 to 192.168.200.238:49881 length 20
Waking up in 3.9 seconds.
(0) Cleaning up request packet ID 149 with timestamp +10 due to cleanup_delay was reached
As you can see no password in that unless I'm missing something which maybe but when I do a radtest I get accept-accept below the debug log from doing it that way
radtest testing test localhost 2 testing123 root#docker-host
Sent Access-Request Id 76 from 0.0.0.0:39308 to 127.0.0.1:1812 length 77
User-Name = "testing"
User-Password = "test"
NAS-IP-Address = 127.0.1.1
NAS-Port = 2
Message-Authenticator = 0x00
Cleartext-Password = "test"
Received Access-Accept Id 76 from 127.0.0.1:1812 to 127.0.0.1:39308 length 20
Ready to process requests
q(1) Received Access-Request Id 163 from 127.0.0.1:53905 to 127.0.0.1:1812 length 77
(1) User-Name = "testing"
(1) User-Password = "test"
(1) NAS-IP-Address = 127.0.1.1
(1) NAS-Port = 2
(1) Message-Authenticator = 0xfade5a334cefa11b8d1c07ea3ca02fae
(1) # Executing section authorize from file /etc/freeradius/3.0/sites-enabled/my_server
(1) authorize {
rlm_ldap (ldap): Reserved connection (1)
(1) ldap: EXPAND (cn=%{%{Stripped-User-Name}:-%{User-Name}})
(1) ldap: --> (cn=testing)
(1) ldap: Performing search in "ou=users,dc=ldap,DC=alexosaurous,DC=co,DC=nz" with filter "(cn=testing)", scope "sub"
(1) ldap: Waiting for search result...
(1) ldap: User object found at DN "cn=testing,ou=users,dc=ldap,dc=alexosaurous,dc=co,dc=nz"
(1) ldap: Processing user attributes
(1) ldap: WARNING: No "known good" password added. Ensure the admin user has permission to read the password attribute
(1) ldap: WARNING: PAP authentication will *NOT* work with Active Directory (if that is what you were trying to configure)
rlm_ldap (ldap): Released connection (1)
rlm_ldap (ldap): Closing connection (2) - Too many unused connections.
rlm_ldap (ldap): You probably need to lower "min"
rlm_ldap (ldap): Closing expired connection (4) - Hit idle_timeout limit
rlm_ldap (ldap): You probably need to lower "min"
rlm_ldap (ldap): Closing expired connection (3) - Hit idle_timeout limit
(1) [ldap] = ok
(1) if ((ok || updated) && User-Password) {
(1) if ((ok || updated) && User-Password) -> TRUE
(1) if ((ok || updated) && User-Password) {
(1) update {
(1) control:Auth-Type := LDAP
(1) } # update = noop
(1) } # if ((ok || updated) && User-Password) = noop
(1) } # authorize = ok
(1) Found Auth-Type = LDAP
(1) # Executing group from file /etc/freeradius/3.0/sites-enabled/my_server
(1) Auth-Type LDAP {
rlm_ldap (ldap): Reserved connection (0)
(1) ldap: Login attempt by "testing"
(1) ldap: Using user DN from request "cn=testing,ou=users,dc=ldap,dc=alexosaurous,dc=co,dc=nz"
(1) ldap: Waiting for bind result...
(1) ldap: Bind successful
(1) ldap: Bind as user "cn=testing,ou=users,dc=ldap,dc=alexosaurous,dc=co,dc=nz" was successful
rlm_ldap (ldap): Released connection (0)
(1) [ldap] = ok
(1) } # Auth-Type LDAP = ok
(1) Sent Access-Accept Id 163 from 127.0.0.1:1812 to 127.0.0.1:53905 length 20
(1) Finished request
Waking up in 4.9 seconds.
(1) Cleaning up request packet ID 163 with timestamp +67 due to cleanup_delay was reached
Ready to process requests
(2) Received Access-Request Id 210 from 127.0.0.1:49536 to 127.0.0.1:1812 length 77
Dropping packet without response because of error: Received packet from 127.0.0.1 with invalid Message-Authenticator! (Shared secret is incorrect.)
Waking up in 0.3 seconds.
(2) Cleaning up request packet ID 210 with timestamp +109 due to done
Ready to process requests
In that request looks like it got the password and had put it in LDAP then authed the username and password
I'm so very lost as to way the phone over wifi is not sending the password
config below
sites enabled
server my_server {
listen {
type = auth
ipaddr = *
port = 1812
}
authorize {
ldap
if ((ok || updated) && User-Password) {
update {
control:Auth-Type := ldap
}
}
}
authenticate {
Auth-Type LDAP {
ldap
}
}
}
LDAP config
# -*- text -*-
#
# $Id: 1f0ee0383834684c7314a89be40003933023c401 $
#
# Lightweight Directory Access Protocol (LDAP)
#
ldap {
# Note that this needs to match the name(s) in the LDAP server
# certificate, if you're using ldaps. See OpenLDAP documentation
# for the behavioral semantics of specifying more than one host.
server = "auth.domain"
# Port to connect on, defaults to 389. Setting this to 636 will enable
# LDAPS if start_tls (see below) is not able to be used.
port = "389"
# Administrator account for searching and possibly modifying.
identity = "cn=myserviceaccount,dc=domain"
password = ""
# Unless overridden in another section, the dn from which all
# searches will start from.
base_dn = "dc=ldap,dc=alexosaurous,dc=co,dc=nz"
#
# Generic valuepair attribute
#
# If set, this will attribute will be retrieved in addition to any
# mapped attributes.
#
# Values should be in the format:
# <radius attr> <op> <value>
#
# Where:
# <radius attr>: Is the attribute you wish to create
# with any valid list and request qualifiers.
# <op>: Is any assignment attribute (=, :=, +=, -=).
# <value>: Is the value to parse into the new valuepair.
# If the attribute name is wrapped in double
# quotes it will be xlat expanded.
# valuepair_attribute = "radiusAttribute"
#
# Mapping of LDAP directory attributes to RADIUS dictionary attributes.
#
# WARNING: Although this format is almost identical to the unlang
# update section format, it does *NOT* mean that you can use other
# unlang constructs in module configuration files.
#
# Configuration items are in the format:
# <radius attr> <op> <ldap attr>
#
# Where:
# <radius attr>: Is the destination RADIUS attribute
# with any valid list and request qualifiers.
# <op>: Is any assignment attribute (=, :=, +=, -=).
# <ldap attr>: Is the attribute associated with user or
# profile objects in the LDAP directory.
# If the attribute name is wrapped in double
# quotes it will be xlat expanded.
#
# Request and list qualifiers may also be placed after the 'update'
# section name to set defaults destination requests/lists
# for unqualified RADIUS attributes.
#
# Note: LDAP attribute names should be single quoted unless you want
# the name value to be derived from an xlat expansion, or an
# attribute ref.
update {
control:Password-With-Header += 'userPassword'
# control:NT-Password := 'ntPassword'
# reply:Reply-Message := 'radiusReplyMessage'
# reply:Tunnel-Type := 'radiusTunnelType'
# reply:Tunnel-Medium-Type := 'radiusTunnelMediumType'
# reply:Tunnel-Private-Group-ID := 'radiusTunnelPrivategroupId'
# These are provided for backwards compatibility.
# Where only a list is specified as the RADIUS attribute,
# the value of the LDAP attribute is parsed as a valuepair
# in the same format as the 'valuepair_attribute' (above).
# control: += 'radiusCheckAttributes'
# reply: += 'radiusReplyAttributes'
}
# Set to yes if you have eDirectory and want to use the universal
# password mechanism.
# edir = no
# Set to yes if you want to bind as the user after retrieving the
# Cleartext-Password. This will consume the login grace, and
# verify user authorization.
# edir_autz = no
# Note: set_auth_type was removed in v3.x.x
# Equivalent functionality can be achieved by adding the following
# stanza to the authorize {} section of your virtual server.
#
# ldap
# if ((ok || updated) && User-Password) {
# update {
# control:Auth-Type := ldap
# }
# }
#
# User object identification.
#
user {
# Where to start searching in the tree for users
base_dn = "ou=users,dc=ldap,DC=alexosaurous,DC=co,DC=nz"
# Filter for user objects, should be specific enough
# to identify a single user object.
filter = "(cn=%{%{Stripped-User-Name}:-%{User-Name}})"
# Search scope, may be 'base', 'one', sub' or 'children'
# scope = 'sub'
# If this is undefined, anyone is authorised.
# If it is defined, the contents of this attribute
# determine whether or not the user is authorised
# access_attribute = "dialupAccess"
# Control whether the presence of "access_attribute"
# allows access, or denys access.
#
# If "yes", and the access_attribute is present, or
# "no" and the access_attribute is absent then access
# will be allowed.
#
# If "yes", and the access_attribute is absent, or
# "no" and the access_attribute is present, then
# access will not be allowed.
#
# If the value of the access_attribute is "false", it
# will negate the result.
#
# e.g.
# access_positive = yes
# access_attribute = userAccessAllowed
#
# userAccessAllowed = false
#
# Will result in the user being locked out.
# access_positive = yes
}
#
# User membership checking.
#
group {
# Where to start searching in the tree for groups
base_dn = "ou=Groups,dc=ldap,DC=alexosaurous,DC=co,DC=nz"
# Filter for group objects, should match all available
# group objects a user might be a member of.
filter = "(objectClass=posixGroup)"
# Search scope, may be 'base', 'one', sub' or 'children'
# scope = 'sub'
# Attribute that uniquely identifies a group.
# Is used when converting group DNs to group
# names.
name_attribute = cn
# Filter to find group objects a user is a member of.
# That is, group objects with attributes that
# identify members (the inverse of membership_attribute).
membership_filter = "(|(member=%{control:Ldap-UserDn})(memberUid=%{%{Stripped-User-Name}:-%{User-Name}}))"
# The attribute in user objects which contain the names
# or DNs of groups a user is a member of.
#
# Unless a conversion between group name and group DN is
# needed, there's no requirement for the group objects
# referenced to actually exist.
# membership_attribute = "memberOf"
# If cacheable_name or cacheable_dn are enabled,
# all group information for the user will be
# retrieved from the directory and written to LDAP-Group
# attributes appropriate for the instance of rlm_ldap.
#
# For group comparisons these attributes will be checked
# instead of querying the LDAP directory directly.
#
# This feature is intended to be used with rlm_cache.
#
# If you wish to use this feature, you should enable
# the type that matches the format of your check items
# i.e. if your groups are specified as DNs then enable
# cacheable_dn else enable cacheable_name.
# cacheable_name = "no"
# cacheable_dn = "no"
# Override the normal cache attribute (<inst>-LDAP-Group)
# and create a custom attribute. This can help if multiple
# module instances are used in fail-over.
# cache_attribute = "LDAP-Cached-Membership"
}
#
# User profiles. RADIUS profile objects contain sets of attributes
# to insert into the request. These attributes are mapped using
# the same mapping scheme applied to user objects.
#
profile {
# Filter for RADIUS profile objects
# filter = "(objectclass=radiusprofile)"
# The default profile applied to all users.
# default = "cn=radprofile,dc=example,dc=org"
# The list of profiles which are applied (after the default)
# to all users.
# The "User-Profile" attribute in the control list
# will override this setting at run-time.
# attribute = "radiusProfileDn"
}
#
# Bulk load clients from the directory
#
client {
# Where to start searching in the tree for clients
base_dn = "ou=Clients,dc=example,dc=com"
#
# Filter to match client objects
#
filter = '(objectClass=frClient)'
# Search scope, may be 'base', 'one', 'sub' or 'children'
# scope = 'sub'
#
# Client attribute mappings are in the format:
# <client attribute> = <ldap attribute>
#
# Arbitrary attributes (accessible by %{client:<attr>}) are not yet supported.
#
# The following attributes are required:
# * identifier - IPv4 address, or IPv4 address with prefix, or hostname.
# * secret - RADIUS shared secret.
#
# The following attributes are optional:
# * shortname - Friendly name associated with the client
# * nas_type - NAS Type
# * virtual_server - Virtual server to associate the client with
# * require_message_authenticator - Whether we require the Message-Authenticator
# attribute to be present in requests from the client.
#
# Schemas are available in doc/schemas/ldap for openldap and eDirectory
#
attribute {
identifier = 'radiusClientIdentifier'
secret = 'radiusClientSecret'
# shortname = 'radiusClientShortname'
# nas_type = 'radiusClientType'
# virtual_server = 'radiusClientVirtualServer'
# require_message_authenticator = 'radiusClientRequireMa'
}
}
# Load clients on startup
# read_clients = no
#
# Modify user object on receiving Accounting-Request
#
# Useful for recording things like the last time the user logged
# in, or the Acct-Session-ID for CoA/DM.
#
# LDAP modification items are in the format:
# <ldap attr> <op> <value>
#
# Where:
# <ldap attr>: The LDAP attribute to add modify or delete.
# <op>: One of the assignment operators:
# (:=, +=, -=, ++).
# Note: '=' is *not* supported.
# <value>: The value to add modify or delete.
#
# WARNING: If using the ':=' operator with a multi-valued LDAP
# attribute, all instances of the attribute will be removed and
# replaced with a single attribute.
accounting {
reference = "%{tolower:type.%{Acct-Status-Type}}"
type {
start {
update {
description := "Online at %S"
}
}
interim-update {
update {
description := "Last seen at %S"
}
}
stop {
update {
description := "Offline at %S"
}
}
}
}
#
# Post-Auth can modify LDAP objects too
#
post-auth {
update {
description := "Authenticated at %S"
}
}
#
# LDAP connection-specific options.
#
# These options set timeouts, keep-alives, etc. for the connections.
#
options {
# Control under which situations aliases are followed.
# May be one of 'never', 'searching', 'finding' or 'always'
# default: libldap's default which is usually 'never'.
#
# LDAP_OPT_DEREF is set to this value.
# dereference = 'always'
#
# The following two configuration items control whether the
# server follows references returned by LDAP directory.
# They are mostly for Active Directory compatibility.
# If you set these to "no", then searches will likely return
# "operations error", instead of a useful result.
#
chase_referrals = yes
rebind = yes
# Seconds to wait for LDAP query to finish. default: 20
timeout = 10
# Seconds LDAP server has to process the query (server-side
# time limit). default: 20
#
# LDAP_OPT_TIMELIMIT is set to this value.
timelimit = 3
# Seconds to wait for response of the server. (network
# failures) default: 10
#
# LDAP_OPT_NETWORK_TIMEOUT is set to this value.
net_timeout = 1
# LDAP_OPT_X_KEEPALIVE_IDLE
idle = 60
# LDAP_OPT_X_KEEPALIVE_PROBES
probes = 3
# LDAP_OPT_X_KEEPALIVE_INTERVAL
interval = 3
# ldap_debug: debug flag for LDAP SDK
# (see OpenLDAP documentation). Set this to enable
# huge amounts of LDAP debugging on the screen.
# You should only use this if you are an LDAP expert.
#
# default: 0x0000 (no debugging messages)
# Example:(LDAP_DEBUG_FILTER+LDAP_DEBUG_CONNS)
ldap_debug = 0x0028
}
#
# This subsection configures the tls related items
# that control how FreeRADIUS connects to an LDAP
# server. It contains all of the "tls_*" configuration
# entries used in older versions of FreeRADIUS. Those
# configuration entries can still be used, but we recommend
# using these.
#
tls {
# Set this to 'yes' to use TLS encrypted connections
# to the LDAP database by using the StartTLS extended
# operation.
#
# The StartTLS operation is supposed to be
# used with normal ldap connections instead of
# using ldaps (port 636) connections
start_tls = no
# ca_file = ${certdir}/cacert.pem
# ca_path = ${certdir}
# certificate_file = /path/to/radius.crt
# private_key_file = /path/to/radius.key
# random_file = ${certdir}/random
# Certificate Verification requirements. Can be:
# "never" (don't even bother trying)
# "allow" (try, but don't fail if the certificate
# can't be verified)
# "demand" (fail if the certificate doesn't verify.)
#
# The default is "allow"
# require_cert = "demand"
}
# As of version 3.0, the "pool" section has replaced the
# following configuration items:
#
# ldap_connections_number
# The connection pool is new for 3.0, and will be used in many
# modules, for all kinds of connection-related activity.
#
# When the server is not threaded, the connection pool
# limits are ignored, and only one connection is used.
pool {
# Number of connections to start
start = 5
# Minimum number of connections to keep open
min = 4
# Maximum number of connections
#
# If these connections are all in use and a new one
# is requested, the request will NOT get a connection.
#
# Setting 'max' to LESS than the number of threads means
# that some threads may starve, and you will see errors
# like "No connections available and at max connection limit"
#
# Setting 'max' to MORE than the number of threads means
# that there are more connections than necessary.
max = ${thread[pool].max_servers}
# Spare connections to be left idle
#
# NOTE: Idle connections WILL be closed if "idle_timeout"
# is set.
spare = 3
# Number of uses before the connection is closed
#
# 0 means "infinite"
uses = 0
# The lifetime (in seconds) of the connection
lifetime = 0
# Idle timeout (in seconds). A connection which is
# unused for this length of time will be closed.
idle_timeout = 60
# NOTE: All configuration settings are enforced. If a
# connection is closed because of "idle_timeout",
# "uses", or "lifetime", then the total number of
# connections MAY fall below "min". When that
# happens, it will open a new connection. It will
# also log a WARNING message.
#
# The solution is to either lower the "min" connections,
# or increase lifetime/idle_timeout.
}
}
side note my user filter is a bit different as I used authentik LDAP outpost
and as per
https://goauthentik.io/docs/providers/ldap
the username is mapped to cn
Thank you for taking the time to read all of this by the way
Assuming you're using EAP-PEAP, are the passwords being stored in your LDAP directory as either plaintext (not advisable in production) or NTLM hashes?
If they're being stored as SHA hashes for example, you'll run into an issue of no known good password as the supplicant will respond to the access-challenge from the NAS with an NTLM hash which freeradius won't be able to use to calculate the corresponding SHA hash it receives from the LDAP server after binding.
When you're using radtest, you're sending a plaintext password which freeradius can convert to the appropriate hash for comparison.
If you're not using PEAP and/or your passwords are stored in your directory as plaintext or NTLM hashes, you can disregard this.

Change buffer before async call returns its result

I have the following function that creates a new buffer and calls a compilation watcher asynchronously in it. This means that every time I save the file I'm working on the watcher will compile it and returns the result:
(defun dune-watch (exe)
"Will call dune build -w EXE on an async process."
(interactive "sBuild name: ")
(let ((buffer (get-buffer-create "Dune watch")))
(with-current-buffer buffer (compilation-minor-mode t))
(projectile-run-async-shell-command-in-root (concat "dune build -w " exe) buffer)
;; Make this process non blocking for killing
(set-process-query-on-exit-flag (get-buffer-process buffer) nil)
(display-buffer buffer '((display-buffer-below-selected display-buffer-at-bottom)
(inhibit-same-window . t)
(window-height . 0.2)))))
A normal run will look like this (lines preceded by # were added by me):
Success, waiting for filesystem changes...
# save file
********** NEW BUILD (src/ident.ml changed) **********
File "src/ident.ml", line 46, characters 46-48:
46 | let compare t1 t2 = String.compare t1.name t2.na
^^
Error: Unbound record field na
Had errors, waiting for filesystem changes...
# save file
********** NEW BUILD (src/ident.ml changed) **********
Success, waiting for filesystem changes...
Now, this doesn't suit me really well because it messes up with the compilation buffer regexp alist so I tried erasing the buffer any time I save a file:
(defun erase-and-fill-buffer (buffer)
"Blahblah BUFFER."
(with-current-buffer buffer
(erase-buffer)
(insert "Dune watch buffer")
))
(defun dune-watch (exe)
"Will call dune build -w EXE on an async process."
(interactive "sBuild name: ")
(let ((buffer (get-buffer-create "Dune watch")))
(add-hook 'before-save-hook (lambda () (erase-and-fill-buffer buffer)))
(with-current-buffer buffer (compilation-minor-mode t))
(projectile-run-async-shell-command-in-root (concat "dune build -w " exe) buffer)
;; Make this process non blocking for killing
(set-process-query-on-exit-flag (get-buffer-process buffer) nil)
(display-buffer buffer '((display-buffer-below-selected display-buffer-at-bottom)
(inhibit-same-window . t)
(window-height . 0.2)))))
But to my surprise, this doesn't work. Remember that dune build -w is only executed when a file is saved and I'm hooking to before-save-hook. Here's the whole content of the buffer:
after first save:
Success, waiting for filesystem changes...
Dune watch buffer
after second save
********** NEW BUILD (src/ident.ml changed) **********
File "src/ident.ml", line 46, characters 46-47:
46 | let compare t1 t2 = String.compare t1.name t2.n
^
Error: Unbound record field n
Had errors, waiting for filesystem changes...
Dune watch buffer
My insert comes after the asynchronous call even though this call should have happened after the file was saved. I tried to output the result of the asynchronous call in another buffer but I encounter the same problem since I don't know how to copy only the last displayed message and not the whole buffer without erasing it.

how to extract ip address from QueueDiscItem in ns3?

I'm new to NS3 and i was trying to extract ip address of a packet from QueueDiscItem,
when i have:
Ptr< QueueDiscItem > item initiated and call:
item->Print(std::cout);
the output i get is
"tos 0x0 DSCP Default ECN Not-ECT ttl 63 id 265 protocol 6 offset (bytes) 0 flags [none] length: 76 10.1.4.2 > 10.1.2.1 0x7fffc67ec880 Dst addr 02-06-ff:ff:ff:ff:ff:ff proto 2048 txq"
but when i call:
Ipv4Header header;
item->GetPacket()->PeekHeader(header);
header.Print(std::cout);
the output i get is
"tos 0x0 DSCP Default ECN Not-ECT ttl 0 id 0 protocol 0 offset (bytes) 0 flags [none] length: 20 102.102.102.102 > 102.102.102.102"
How to get the Header data
According to the list of TraceSources, the TraceSources associated with QueueDiscItems are for Queues. I'm guessing you were trying to attach to one of those TraceSources.
A QueueDiscItem encapsulates several things: a Ptr<Packet>, a MAC address, and several more things. Since you are using IPv4, the QueueDiscItem is actually an Ipv4QueueDiscItem (the latter is a subclass of the former). So, let's start by casting the QueueDiscItem to an Ipv4QueueDiscItem by
Ptr<const Ipv4QueueDiscItem> ipItem = DynamicCast<const Ipv4QueueDiscItem>(item);
Next, you need to know that at this point in the simulation, the Ipv4Header has not been added to the Ptr<Packet> yet. This is probably a design choice (that I don't understand). So, how can we get this information? Well, the Ipv4QueueDiscItem encapsulates the Ipv4Header, and at some point before passing the Ptr<Packet> to L2, the header is added to the packet. This Header can be retrieved by
const Ipv4Header ipHeader = ipItem->GetHeader();
So, now we have the Ipv4Header of the packet you're interested in. Now, we can safely get the address from the Ipv4QueueDiscItem by
ipHeader.GetSource();
ipHeader.GetDestination();
In summary, your TraceSource function should look something like this:
void
EnqueueTrace (Ptr<const QueueDiscItem> item) {
Ptr<const Ipv4QueueDiscItem> ipItem = DynamicCast<const Ipv4QueueDiscItem>(item);
const Ipv4Header ipHeader = ipItem->GetHeader();
NS_LOG_UNCOND("Packet received at " << Simulator::Now() << " going from " << ipHeader.GetSource() << " to " << ipHeader.GetDestination());
}
Why does item->Print(std::cout); work?
All of the above makes sense, but why does
item->Print(std::cout);
print the correct addresses? First, it is important to realize that here Print() is a function of the QueueDiscItem, not the Packet. If we go to the source of this function, we find that Print() just prints the Header if it has already been added.

Operating Micropython-running WeMos D1 mini (ESP8266) pins with HTTP requests

What I am trying to ultimately achieve is to control my garage door opener with a relay connected to a WeMos D1 Mini, connected to my home WiFi. I am using the openGarageDoor() function. Everything works fine with serial connection.
I have been trying to run HTTP server on a WeMos D1 Mini with this script.
customertagsAction() -- try:
import usocket as socket
except:
import socket
CONTENT = b"""\
HTTP/1.0 200 OK
Hello #%d from MicroPython!
"""
def main(micropython_optimize=False):
s = socket.socket()
# Binding to all interfaces - server will be accessible to other hosts!
ai = socket.getaddrinfo("0.0.0.0", 8080)
print("Bind address info:", ai)
addr = ai[0][-1]
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)
print("Listening, connect your browser to http://<this_host>:8080/")
counter = 0
while True:
res = s.accept()
client_sock = res[0]
client_addr = res[1]
print("Client address:", client_addr)
print("Client socket:", client_sock)
if not micropython_optimize:
# To read line-oriented protocol (like HTTP) from a socket (and
# avoid short read problem), it must be wrapped in a stream (aka
# file-like) object. That's how you do it in CPython:
client_stream = client_sock.makefile("rwb")
else:
# .. but MicroPython socket objects support stream interface
# directly, so calling .makefile() method is not required. If
# you develop application which will run only on MicroPython,
# especially on a resource-constrained embedded device, you
# may take this shortcut to save resources.
client_stream = client_sock
print("Request:")
req = client_stream.readline()
print(req)
while True:
h = client_stream.readline()
if h == b"" or h == b"\r\n":
break
print(h)
client_stream.write(CONTENT % counter)
client_stream.close()
if not micropython_optimize:
client_sock.close()
counter += 1
print()
main()
The requests are received properly and the GET variables are shown on the print(). The best i have been able to do is
req = client_stream.readline()
print(req)
while True:
h = client_stream.readline()
if h == b"" or h == b"\r\n":
break
print(h)
client_stream.write(CONTENT % counter)
//my function here:
if 'opengaragedoor=1' in req:
openGarageDoor()
client_stream.close()
I don't know how to parse the request properly. I only have come up with this dirty solution. This probably causes a timeout on the requesting system, as Postman or such needs to wait for the function to run through.

How to check if can write to a folder

In julia, how do I check if the current is allowed to write to a folder?
I could do the python way, and just attempt to do it, and then fail fail and recover.
(In my case I can definitely recover, I have a list of locations to attempt to write to, as fallbacks. I expect the first few not to work (The first few are shared locations, so only computer admins are likely to have permission to writer there)
Python has also os.access function. Maybe Julia will have something similar in the future. Now we could borrow idea. :)
It is implemented in posixmodule.c (also functionality for windows!) so if you are on posix you could simply mimic:
julia> const R_OK = 4 # readability
julia> const W_OK = 2 # writability
julia> const X_OK = 1 # executability
julia> const F_OK = 4 # existence
julia> access(path, mode) = ccall(:access, Cint, (Cstring, Cint), path, mode) == 0;
Small test:
julia> access("/root", W_OK)
false
julia> access("/tmp", W_OK)
true
(for windows it could be just a little more complicated... But I could not test it now)
EDIT:
Thanks to Matt B. we could use libuv support in Julia which has to be portable (although slower on posix systems):
julia> function uv_access(path, mode)
local ret
req = Libc.malloc(Base._sizeof_uv_fs)
try
ret = ccall(:uv_fs_access, Int32, (Ptr{Void}, Ptr{Void}, Cstring, Int64, Ptr{Void}), Base.eventloop(), req, path, mode, C_NULL)
ccall(:uv_fs_req_cleanup, Void, (Ptr{Void},), req)
finally
Libc.free(req)
end
return ret, ret==0 ? "OK" : Base.struverror(ret)
end
julia> uv_access("/tmp", W_OK)
(0, "OK")
julia> uv_access("/root", W_OK)
(-13, "permission denied")
julia> uv_access("/nonexist", W_OK)
(-2, "no such file or directory")
Is the following sufficient:
julia> testdir(dirpath) = try (p,i) = mktemp(dirpath) ; rm(p) ; true catch false end
testdir (generic function with 1 method)
julia> testdir("/tmp")
true
julia> testdir("/root")
false
Returns true if dirpath is writable (by creating a temporary file inside a try-catch block). To find the first writable directory in a list, the following can be used:
julia> findfirst(testdir, ["/root","/tmp"])
2
Doing apropos("permissions"):
julia> apropos("permissions")
Base.Filesystem.gperm
Base.Filesystem.mkpath
Base.Filesystem.operm
Base.Filesystem.uperm
Base.Filesystem.mkdir
Base.Filesystem.chmod
shows a function called Base.Filesystem.uperm which seems to do exactly what you want it to:
help?> uperm
search: uperm supertype uppercase UpperTriangular isupper unescape_string unsafe_pointer_to_objref
uperm(file)
Gets the permissions of the owner of the file as a bitfield of
Value Description
––––– ––––––––––––––––––
01 Execute Permission
02 Write Permission
04 Read Permission
For allowed arguments, see stat.
Unfortunately it seems to be a bit buggy on my (old v7 nightly) build:
julia> uperm("/root")
0x07 # Uhhh I hope not?
I will update my build and raise a bug if one is not already present.
PS. In case it wasn't clear, I would expect to use this in combination with isdir to detect directory permissions specifically
I don't think that Dan Getz's answer will work on Windows because the temporary file created cannot be deleted while there is an open handle to it, but this amended version with a call to close does work:
function isfolderwritable(folder)
try
(p,i) = mktemp(folder)
close(i)
rm(p)
return(true)
catch
return(false)
end
end

Resources