Adding a mapped drive with WNetAddConnection2 is not accessible - network-programming

I'm trying to map a drive using WNetAddCOnnection2 but there's something not quite right. The code that I am using from pinvoke.net and seems to work at first. If I am stepping through the code I get a 0 for a response and I am able to use System.IO.Directory.GetFiles() to inspect the new mapped drive which leads me to believe that credentials are fine.
The problem is that the drive is not available outside of the application. When I type net use from a command prompt I see the drive listed like this:
Unavailable L: \\<server>\<share> Microsoft Windows Network
When I try to access the drive I get either:
The system cannot find the drive specified.
or
The system cannot find the path specified.
Any help would be greatly appreciated.
Here's the nutshell of the code in question:
NETRESOURCE res = new NETRESOURCE();
res.iScope = RESOURCE_GLOBALNET;
res.iType = RESOURCETYPE_DISK;
res.iDisplayType = RESOURCEDISPLAYTYPE_SHARE;
res.iUsage = RESOURCEUSAGE_CONNECTABLE;
res.sRemoteName = share;
res.sLocalName = drive;
res.sProvider = null;
int iFlags = 0;
iFlags = CONNECT_UPDATE_PROFILE;
int iResult = WNetAddConnection2( ref res, psPassword, psUsername, iFlags );
The iResult always ends up equaling 0.

MSDN articles that may assist:
* WNetAddConnection2 - [http://msdn.microsoft.com/en-us/library/aa385413%28VS.85%29.aspx][1]
* NETRESOURCE - [http://msdn.microsoft.com/en-us/library/aa385353%28VS.85%29.aspx][2]
I reckon your problem is the display type where "res.iDisplayType = RESOURCEDISPLAYTYPE_SHARE". Perhaps try changing to a value of "0" (RESOURCEDISPLAYTYPE_GENERIC). So for example, what I generally use to map drives appears:
With Res
.dwScope = RES_SCOPE_GLOBALNET 'value 2
.dwType = RES_TYPE_DISK 'value of 1
.dwUsage = RES_USE_CONNECT 'value of 1
.localName = "x:" 'leave blank for no drive
.RemoteName = "\\\"
End With
lRes = WNetAddConnection2(Res, sPassword, sDomain & "\" & sPassword, RES_CNN_UPDATE_PROFILE)
If lRes = 0 Then
'Success
Else
'Error
End If
Always check your connections before & after calls from command prompt:
1a) From system making connection, list current connections:
net use
1b) From system connected too, list current sessions:
net session
To disconnect session, use API 'WNetCancelConnection2', my code following from above:
sServer = "\\\"
lRes = WNetCancelConnection2(sServer, RES_CNN_UPDATE_PROFILE, True)
If lRes `> 0 Then
'Success
Else
'Error
End If
Alternatively, simply making connections using 'net' command:
1) To map a drive letter:
net use `: \\`\` /user:`\` `
2) To map an IPC connection:
net use \\`\` /user:`\` `
Disconnecting using 'net' command:
1) Disconnecting mapped drive:
net use `: /delete
2) Disconnecting server share:
net use \\`\` /delete

Related

Lua program throwing error with stdin after completion

I've written a lua program for OpenComputers in Minecraft which downloads a github repo to the computer, file structure and all. The code:
internet = require("internet")
io = require("io")
filesystem = require("filesystem")
handle = internet.request("https://api.github.com/repos/Vedvart/Minecraft/contents")
result = ""
for chunk in handle do result = result..chunk end
while(not (string.find(result, "download_url") == nil)) do
i, j = string.find(result, "download_url")
qi, qj = string.find(string.sub(result, j+4,-1), '"')
url = string.sub(result, j + 4, j + qi + 2)
if string.sub(url, -14) == '.gitattributes' then goto continue end
ni, nj = string.find(url, "Vedvart")
filepath = string.sub(url, nj+2, -1)
ri, rj = string.find(string.reverse(filepath), "/")
if not filesystem.isDirectory("/home/github/"..string.sub(filepath, 1, -ri)) then
print('had to make')
filesystem.makeDirectory("/home/github/"..string.sub(filepath, 1, -ri))
end
print('here 2')
file_content_handle = internet.request(url)
file_content = ''
for chunk in file_content_handle do file_content = file_content .. chunk end
print(filepath)
print(io)
print(filesystem.isDirectory("/home/github/"..string.sub(filepath, 1, -ri)))
file = io.open('/home/github/'..filepath, 'w')
print(file)
file:write(file_content)
file:close()
print('here 3')
print(file)
::continue::
result = string.sub(result, j+qi+3, -1)
print('here 4')
end
print('done')
The code actually runs fine, reaching the final print statement and successfully generating the file structure and downloading all files. However, after this, the program throws an error:
I've googled around, and struggled to even find the same error being thrown, much less in the same circumstances. It doesn't seem like the error is originating directly in my code, but other code seems to run fine, so something in my program must be triggering this error elsewhere. I'm not sure what is causing it - any help is appreciated.
Not sure why you need to require io. This is not necessary in vanilla Lua and looking at the example snippets at their website it shouldn't be necessary in OpenComputers either.
io = require("io") overwrites any existing global io library and maybe that newly required table does not have a stdin field.
Just an educated guess :)
If your code causes this error after being completed a change in a global variable is one of the few possible reasons.

ADO.Net connection executing DB2 stored procedure returning pooled output parameter values using iSeries connection

[EDIT - This issue is resolved. The problem had to do with uninitialized out parameters on the stored procedure.]
Why would I need to turn connection pooling off to get this to work correctly???
[EDIT - connection pooling released a shared connection memory area on the AS400]
In my MVC web app I call a DB2 Stored Procedure (SP).
This SP has multiple in and out parameters similar to this pseudo code:
CreatePO(#REQNO[in], #PO[out], #Approver[out], #ErrorMsg[out])
My app writes data to tables used by this SP during its processing so when all the data is in place I call the SP and it tries to create a PO.
If the PO creation fails there will be an error message in the #ErrorMsg out parameter. In these cases the #PO and #Approver parameters should be blank.
Here's what happens in sequence:
1) I try to create my first PO but there is a problem...
CreatePO(100, blank, blank, blank)
which results in...
CreatePO(100, blank, blank, 'unable to determine approver')
2) I successfully create the 2nd PO...
CreatePO(101, blank, blank, blank)
CreatePO(101, 'P1234', 'JJONES', blank)
3) I try to re-create a PO for #REQNO 100
CreatePO(100, blank, blank, blank)
CreatePO(100, 'P1234', 'JJONES', 'unable to determine approver')
Step 3 has conflicting out parameters. The app pool is returning the PO and Approver from Step 2 along with the appropriate an error message.
If I recycle my IIS app pool then the results are back to what happened in Step #1.
I am able to get expected results I add "pooling=false" to the connection string. But why would output parameters be affected in this manner by connection pooling? This seems more like a bug than some sort of desirable caching method.
If I don't paste my code someone will get bent out of shape so here it is...
(Look at the end of the top two lines)
'Dim cs As String = "DataSource=mydb;UserID=myuser;Password=mypassword;Naming=System;ConnectionTimeout=180; DefaultIsolationLevel=ReadUncommitted;AllowUnsupportedChar=True;CharBitDataAsString=True; TransactionCompletionTimeout=0;pooling=false"
Dim cs As String = "DataSource=mydb;UserID=myuser;Password=mypassword;Naming=System;ConnectionTimeout=180; DefaultIsolationLevel=ReadUncommitted;AllowUnsupportedChar=True;CharBitDataAsString=True; TransactionCompletionTimeout=0;"
Using conn As New iDB2Connection(cs)
conn.Open()
Dim cmd As iDB2Command = New iDB2Command()
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "BF6360CL"
' Input parameters
cmd.Parameters.Add(New iDB2Parameter With {.ParameterName = "#REQNO", .DbType = SqlDbType.Char, .Size = 7, .Value = model.RO})
' Output parameters
Dim opo = New iDB2Parameter With {.ParameterName = "#POORDER", .DbType = SqlDbType.Char, .Size = 7, .Direction = ParameterDirection.Output}
cmd.Parameters.Add(opo)
Dim oApprover = New iDB2Parameter With {.ParameterName = "#APPROVER", .DbType = SqlDbType.Char, .Size = 10, .Direction = ParameterDirection.Output}
cmd.Parameters.Add(oApprover)
Dim oStatus = New iDB2Parameter With {.ParameterName = "#STATUS", .DbType = SqlDbType.Char, .Size = 3, .Direction = ParameterDirection.Output}
cmd.Parameters.Add(oStatus)
Dim oErr = New iDB2Parameter With {.ParameterName = "#ERROR", .DbType = SqlDbType.Char, .Size = 1, .Direction = ParameterDirection.Output}
cmd.Parameters.Add(oErr)
' return value
Dim oRetval = New iDB2Parameter With {.ParameterName = "#RETURN_VALUE", .DbType = SqlDbType.Char, .Size = 10, .Direction = ParameterDirection.ReturnValue}
cmd.Parameters.Add(oRetval)
cmd.ExecuteNonQuery()
model.PO = opo.Value
model.Approver = oApprover.Value
model.Status = oStatus.Value
model.Err = oErr.Value
End Using
return model
So the big question is this:
Why on earth would connection pooling be responsible for out parameter values???
Could this be a bug in the IBM iSeries iDB2Connection implementation?
The IIS application pool is caching stored procedure output parameters by name and returning a cached value when nulls are detected. This happens with ODBC or iSeries connections. When I recycled the application pool this cached value went away. I added to the connection string “pooling=false;” and these cached values would no longer appear.
My boss asked me to try calling the stored procedure using iSeries Navigator just to see what the out parameters contain. Boy was I surprised.
It turned out that the Stored Procedure (SP) was at fault after all. I sat with the AS400 RPG developer this morning and watched them debug the SP. The problem had to do with uninitialized memory.
Here's the definition of the SP:
BF6360CL(#REQNO, #USER, #ENVIRONMENT, #PO[out], #Approver[out], #Status[out], #Error[out])
I then reset my connection to the AS400 in iSeries Navigator and the output parameters reset back to
4 = S2.RETU
5 = RN_VAR0000
etc...
The AS400 developer is making changes now to initialize the variables. When they're done I expect to be able to change my program back to use connection pooling.
When I reset the IIS App Pool it reset my connection to the database. This seemed to release allocated memory on the AS400.
If anyone has more specifics about Connections and AS400 output parameter memory please share.

Assign variable with punctuation in between it in lua

I'm trying to write a script for DC++ hub based on Ptokax running on lua
i'm trying to assign the nick(a variable) which has punctuation in between but it gives nil values
(sPattern is ! already assigned in script)
sData = "[11:03:30] !spm sTo_Nick sFromNick message to be sent"
cmd,sToNick1,sToNick2,sFromNick ,sMessage = string.match(sData, "%b<>%s["..sPattern.."](%a*)(%s+)(%w*)(%s+)(%w*)(%s+)(%.*)")
what i want to be assigned is
cmd = spm
sToNick1 = sTo ,
sToNick2 = Nick ,
sFromNick = sFromNick ,
sMessage = message to be sent
what i'm getting is
spm sTo _ Nick
as can be seen here https://repl.it/BrAg/3
can anyone please suggest the edit or help.
You need to rearrange the capture groups:
cmd,sToNick1,sToNick2,sFromNick,sMessage =
string.match(sData, "%b<>%s["..sPattern.."](%a*)%s+(%w*)"..pattern.."(%w*)%s+(%w*)%s+(.*)")
See the updated demo

Lua script to extract info from wireshark .pcap traces

I want to get the frame time (relative) of the first packet that is not communicating on sos and DIS ports and ip address is not the one mentioned in the if statement. But the packet should be utilizing port 24111. However, the code below is not working for this purpose. It works, until I add udp_port~=24111. After that it gives me no results, which means that it doesn't go inside that conditional statement. I have tried to write the condition in multiple ways, even separating it out into a new if statement but it doesn't work. What I am doing wrong here. Thanks for suggestions in advance.
Here is the piece of code that I have at the moment
local first_outpacket = 0
local flag = 0
function stats_first_packet()
local udp_port
local frame_time
local ip_addr
frame_time = time_relative_extractor()
udp_port = udp_port_extractor()
ip_addr = ip_addr_extractor()
if ( udp_port ) then
if (not (udp_port == 3000 or udp_port==3838 or flag==1 or ip_addr=="192.168.1.2" or udp_port~=24111)) then
first_outpacket = frame_time
print(frame_time)
flag = 1
else
-- print("tcp_src_port already recorded")
end
else
-- print("no tcp_src_port")
end
end
The problem apparently lies in the data type returned by the extractor() functions. In order to compare them with another value in the if statement they have to be converted into strings using tostring() function.
For example:
if (not (tostring(udp_port) == "3000" or tostring(udp_port)=="3838" or flag==1))

How can I get a wireshark Lua dissector protocol preferences to save and persist when I close wireshark?

So I have written what I can only refer to as an Awesome dissector. It doesn't do much, yet it boosts my work efficiency greatly.
My only problem is that I exposed a few preferences, and they won't stick through wireshark close/start.
I.E. :
Prerequisite : Lua script must be in plugins dir...
Open wireshark, Edit > Preferences > Protocol > http.queryparameters...
Set Param1 Value to "aaa", click OK. (It will affect dissection properly.)
Close wireshark, Start again, the value is again something else.
My dissector :
-- Written by Eitam Doodai
-- trivial postdissector example
-- declare some Fields to be read
full_uri_from_request = Field.new("http.request.full_uri")
-- declare our (pseudo) protocol
http_query_params_proto = Proto("http.query_parameters","HTTP Query Parameters Postdissector")
-- create the fields for our "protocol"
query_param1 = ProtoField.string("http.query_parameters.param1","PARAM1")
query_param2 = ProtoField.string("http.query_parameters.param2","PARAM2")
query_param3 = ProtoField.string("http.query_parameters.param3","PARAM3")
-- add the field to the protocol
http_query_params_proto.fields = {query_param1}
http_query_params_proto.fields = {query_param2}
http_query_params_proto.fields = {query_param3}
-- Add prefs
local p1 = http_query_params_proto.prefs
p1.value1 = Pref.string ("Param1 Value", "123", "Param key to extract")
p1.value2 = Pref.string ("Param2 Value", "456", "Param key to extract")
p1.value3 = Pref.string ("Param3 Value", "789", "Param key to extract")
-- create a function to "postdissect" each frame
function http_query_params_proto.dissector(buffer,pinfo,tree)
-- obtain the current values the protocol fields
local full_uri_value = full_uri_from_request()
if full_uri_value then
local value = tostring(full_uri_value)
local subtree = tree:add(http_query_params_proto,"Query Param1")
local subtree = tree:add(http_query_params_proto,"Query Param2")
local subtree = tree:add(http_query_params_proto,"Query Param3")
_, _, query_param1_str = string.find(value,p1.value1 .. "=([^&]+)")
_, _, query_param2_str = string.find(value,p1.value2 .. "=([^&]+)")
_, _, query_param3_str = string.find(value,p1.value3 .. "=([^&]+)")
if query_param1_str then
subtree:add(query_param1,query_param1_str)
end
if query_param2_str then
subtree:add(query_param2,query_param2_str)
end
if query_param3_str then
subtree:add(query_param3,query_param3_str)
end
end
end
-- register our protocol as a postdissector
register_postdissector(http_query_params_proto)
If you have a console open and start wireshark from the command line, after you change one of your http.query_parameters.param settings, save it and close wireshark, and restart it, you'll see something like:
...preferences line 1829: No such preference "http.query_parameters.value2" (applying your preferences once should remove this warning)
And that's a problem: wireshark prints that out for preferences it finds in the saved preference file that it doesn't understand/know-about.
Edit: do NOT open a bug about this. The problem is you used a Protocol name that already exists with preferences: "http". In other words, since you're basically naming the preferences http.query..., wireshark thinks it should belong to the http protocol module, but the real http module doesn't know anything about it, so wireshark prints that error the next time it tries reading from the preferences file.
Long story short: change the name of your Proto and fields and so on, to not collide with a real protocol name.

Resources