Issue detecting / communicating with card reader using pcsc-lite on RHEL 6 linux using C++ - c++

I am trying to develop an application that would interface with a Smart Card Reader and read information from the smart card.
Let me give you the development environment and the hardware used.
OS: Red Hat Enterprise Linux 6
IDE: Eclipse Juno CDT
Language: C/C++
Hardware:
Smart Card Reader: Omnikey 5321 (https://www.hidglobal.com/products/readers/omnikey/5321)
I have installed the driver and can find the following directories / files:
/usr/lib64/pcsc/drivers/ifd-ccid.bundle
/usr/lib64/pcsc/drivers/ifdokrfid_lnx_x64-2.10.0.1.bundle/Contents
/usr/lib64/pcsc/drivers/ifdokrfid_lnx_x64-2.10.0.1.bundle/Contents/info.plist
/usr/lib64/pcsc/drivers/ifdokrfid_lnx_x64-2.10.0.1.bundle/Contents/Linux
Contents of info.plist clearly show the "OMNIKEY CardMan 5x21" string under "ifdFriendlyName" key.
I want to use the PC/SC standard. Hence I have downloaded and installed the PCSC-lite and I have the checked that the daemon (pcscd) is running and the service status is ok.
Now comes the interesting part...
In my code, I used the following APIs in sequence.
SCARDCONTEXT oSCardContext;
SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, & SCardContext);
SCardEstablishContext() returns SCARD_S_SUCCESS. Great!
SCARDCONTEXT oSCardContext;
DWORD dwReaders = SCARD_AUTOALLOCATE;
LPSTR mszReaders;
SCardListReaders(oSCardContext, NULL, (LPSTR) & mszReaders, & dwReaders);
SCardListReaders() returns SCARD_E_NO_READERS_AVAILABLE. Not good.
At this point I go and check that the reader is properly connected. Yes it is.
I verify if I can see any reader entries in the /etc/reader.conf but I find no readers listed in here.
I then go to /etc/reader.conf.d but find no files in here as well.
So the smart card context is empty, I presume and hence no readers are listed.
So the issue right now is that pcsc-lite cannot detect(?) my reader attached and for which driver has been installed?
Just to check I wrote a simple program using the udev library to read all the "usb" subsystem entries and am able to find the following info from udev about the card reader connected:
Device Node Path:(null)
Vendor ID:076b
Product ID:5321
Manufacturer:OMNIKEY
Product:Smart Card Reader USB
serial:(null)
So am sure the device is detectable. But why is it that PC/SC Resource Manager cannot create this context?
So, How do I resolve this?
I am new to Linux, and have been trying to solve this issue myself without asking for help. But then I see that when there is time constraint it is indeed wise to better seek help from experts and people who have worked and / or encountered such an issue.
I have been googling too much but have not seen any that have my issue. So I presume I am missing something really basic perhaps.
If there is something I need to provide, please let me know. I will do so ASAP.
I appreciate your time to read.
Regards.
EDIT :
I have updates...
I did the following:
1. I got a new card reader (SCM Microsystems) and still it was not detected.
2. The pcscd daemon was started at boot time by default. I stopped the service after I logged in, and then run in foreground mode using the command "pcscd -a -f -d" and the SCM reader was detected successfully.
3. I tried to plugin the reader in my question above, the OMNIKIEY 5321, and it was not detected.
Apprently, I arrived at the following conclusion:
1. For some reason until pcscd was stopped and run in foreground mode manually after I logged in, the readers were not detected.
2. The OMNIKEY reader / driver has a problem.
Regards.

Related

How to get Nokia S30+'s MRE vxp file to run on nokia 225?

The setup
Ok let's me talk a bit about the setup:
I have installed Visual Studio 2008 (the edition that let you try for 90 days), MRE SDK 3.0 from this Github issue, Sourcery Codebench Lite for ARM EABI and also ARM Realview Development suite 3.1 (but it requires license, and I am too lazy to cr#ck it, also I prefer the open source GCC to that commercial software). I set the compiler to Sourcery Codebench's GCC.
I can compile and run vxp file on Mediatek's emulator without any problem.
The problem
After compile for ARM platform, here's the output in [project_dir]\arm:
I tried copying the Default.vxp to my Nokia 255's SD card, then open that file on my phone, but the phone said Can't open this app at the moment.
I also try creating an appmanager folder on my SD card, then my phone's internal storage, then copy the vxp file there, but in the app list, there is still no app other than stock apps, and the vxp file still not run.
Other vxp files
I downloaded some vxp files from http://shifat100.xtgem.com/, put to my SD card and run from it. Some will work, for example the Asphalt 6 Game, but some won't, for example the Gold rush game, they yelt Can't open this app at the moment.
I checked the format of the Asphalt 6 game 's vxp with the file command, and it said data. But I check my Default.vxp, it was ELF. I think this is the problem, but don't know how to convert/pack ELF to vxp.
Using binwalk with the Asphalt 6 game 's vxp, I get 2 zlib compressed files and 2 GIFs, which are icons of the game. The two compressed files, after unpack, one contain many names, for example
splash_320x240.bsprite
splash_menu_320x240_200k.bsprite
splash_menu_split_320x240_200k.bsprite
splash_title.bsprite
hollywood_320x240_200k.bsprite
new.png
font_small.bsprite
font_large.bsprite
interface_font.bsprite
copter.bsprite
car_tourist.bsprite
cars_fx.bsprite
cars_shadow.bsprite
so I think this is the resource file. The other might contain code, I found some exception strings in it, for example
Unknown signal
Invalid Operation
Divide By Zero
Overflow
Underflow
Inexact Result
: Heap memory corrupted
Abnormal termination
Arithmetic exception:
Illegal instruction
Interrupt received
Illegal address
Termination request
Stack overflow
Redirect: can't open:
Out of heap memory
User-defined signal 1
User-defined signal 2
Pure virtual fn called
C++ library exception
and some (maybe) S30+ platform APIs, for example
vm_get_mre_modules
vm_get_mre_total_mem_size
vm_get_mre_version
So what might be the problem? Screen resolution? I changed it but still not work. SDK version? I also tried all 3 version, but no luck. File format? Compiler difference? (Note that I'm using GCC while most tutorial left on the internet suggest using RVCS) I don't know.
Any ideas? Thanks!
If you need to get any files, tell me and I will put it here.
Delivered from my answer at RE.SE
First I want to say thanks to people at 4pda forum. See their thread here.
Can you figure out informations about the MRE VXP format
Well I haven't found yet, need further research
how to get it signed
Short answer:
Step 1: Get your SIM 1's IMSI number (NOT IMEI, they are DIFFERENT!)
You can do this in multiple ways, but the easiest way is to plug the SIM 1 in to an Android phone and read. I personally use ADB to read IMSI (worked on Android 6+ without root):
adb shell service call iphonesubinfo 7
Step 2: Go to https://vxpatch.luxferre.top/ and input the IMSI number you got in step 1. Then select your VXP file, click 'Patch' and you should be able to download a patched version.
or
You can enter the IMSI number in the project setting, but REMEMBER TO ADD 9 BEFORE THE IMSI NUMBER
Step 3: Move the patched version into a SD card and plug it in your phone
Step 4: Find the vxp file and click open, your app should run now!
Long answer:
Some apps doesn't require specify the IMSI, they just work on any devices. That's because they use another way of signing, using RSA key.
If you are interested, read here. The text is in Russian, so use Google Translate if you want to.
I have tested with ADS 1.2 compiler (I cracked myself, if you want it then tell me) and GCC (Smaller size + work very well) and Nokia 225, will continue to test further!
The apps in S30+ platform are written in C (and optionally C++), so you can port many apps to S30+
Again, a great thanks to people at 4pda forum!
An image of the app running after signing:

Possible to Interface with/use 3rd party Windows driver?

This touches on some already-answered questions, so feel free to duplicate away, but chances are I've already read them and am not satisfied.
There are 2 drivers on my system (located in C:\Windows\System32\drivers) called pefndis.sys and wfpcapture.sys. I am 100% sure pefndis.sys is a kernel driver and 99.9% sure wfpcature.sys is as well. These are 3rd party drivers installed by Mircosoft's Message Analyzer. I have discovered pefndis.sys is used to capture data on the wire and wfpcapture.sys is used to capture data above the network layer (ie, this will capture loopback traffic). I have no documentation, header files, etc, for these drivers as there was no intention of Microsoft for these drivers to be used for custom solutions as I would like to do. It just so happens I've identified wfpcapture.sys as performing the exact tasks I want, and I'd love to tap into what it can do; this seems so much more reasonable than spending the time and pain of implementing my own driver. However, my efforts have failed.
This is what I've done: I have some simple c++ code here:
void Provider::InitDriver()
{
HANDLE wfpHandle = NULL;
DWORD lastError = 0;
LPCTSTR wfpName = L"\\\\.\\wfpcapture";
LPCTSTR pefName = L"\\\\.\\pefndis";
wfpHandle = CreateFile(
wfpName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
lastError = GetLastError();
CloseHandle(wfpHandle);
}
When I run CreateFile with wfpName, I get an invalid handle and lastError==2 meaning the file cannot be found. When I run CreateFile with pefName, I get a valid handle and lastError==0. Upon further investigation, most of my randomly-picked .sys files from the drivers folder produce invalid handles with error codes of 2. Occasionally I'd get an error code of 5 (Access Denied, which also seems odd since I'm running everything as administrator). Does anyone have an explanation why I cannot get a handle to wfpcapture.sys? I brought up the pefndis.sys driver because it was installed by the same program as wfpcapture.sys, and I can clearly get a handle to that, so all my strings are formatted correctly, and both files are in the same directory. I came across this post yesterday which told me IoCreateSymbolicLink can be used in the driver code to give the driver another alias. If I'm using the wrong alias, does that explain why so many .sys files return FILE_NOT_FOUND errors when I try to get handles to them?
I've tried to do some more research on the file using IL DASM (no luck, this is native code), DUMPBIN, WinObj, and DependencyWalker.
DUMPBIN /EXPORTS [...]wfpcapture.sys returns no exports. I find this extremely odd. These answers suggest .DLLs without exports are simply resources or the code is obfuscated. I am almost certain wfpcapture.sys does not just contain resources. Is obfuscation the most reasonable explanation.. any other ideas why it doesn't have any exports?
I could not find wfpcapture in WinObj anywhere. I located pefndis in Device\. Where is wfpcapture? It doesn't actually talk to a device, so that makes sense, but it is still a driver, correct? Do drivers need to register with Windows in some way before CreateFile can find them?
DependencyWalker verified what DUMPBIN told me, I think .. no exports. I have no idea how Message Analyzer (or anything else down its dependency stack) is actually talking to it.
Just a bit more background for a complete picture... wfpcapture.sys is an ETW Provider that taps into Microsoft's WFP architecture (used for firewall and IDS applications) to sniff packets above the network layer. I want code that "activates" wfpcapture.sys and then sits back and collects the events (packet captures) that wfpcapture publishes. It's this activation part that I can't figure out. If I setup Message Analyzer to start capturing localhost traffic, then turn on the part of my code that captures the events (using StartTrace(...) and EnableTraceEx2(...)), that works just fine. I am just dying to know how Message Analyzer is talking to wfpcapture.sys and what it's saying in order to get it to cooperate and start publishing events. Another fun fact: When I start a trace in Message Analyzer and do sc query wfpcapture, it tells me the service (here it is identified as a kernel driver) is running. When I stop the trace, the query tells me the service is stopped. If I manually sc start wfpcapture and verify the service is running,, and then run my event capturing code, I get nothing. This tells me Message Analyzer must be sending something to wfpcapture.sys to get it activated and publishing. My plan that spawned this whole thing was to get a handle to driver and start sending it control codes via DeviceIoControl to glean some knowledge on how it worked. I have also seen some very strong evidence that Message Analyzer is passing filter masks to the driver.
Am I completely wasting my time here? That driver is not meant for my consumption, and poking and prodding it to learn about it may be a long shot, but I'm certain it does exactly what I need and I've never written a driver in my life; trying to do that seems foolish when this is sitting right here. Message Analyzer is free, I'm not trying to steal software. Could there possibly be some DRM associated with the driver that's boxing me out? I'd love to hear the thoughts of anyone out there who has Windows driver experience.
Ok, lot of questions there, hope this doesn't get flagged as too broad.

libnodave communication with S7-1200

For a couple of days i've been trying to use libnodave as communication library to communicate with a S7-1200 PLC of Siemens(CPU 1214C).
With the libnodave library there are a couple of things provided.
The Delphi application is working, the windows executable is working.
On the Vmware I'm running Linux and the precompiled binary of testISO_TCP is working.
Seems like i can use it, right?
daveInterface * di;
daveConnection * dc;
_daveOSserialType fds;
ds.rfd=openSocket(102, "192.168.0.1");
fds.wfd=fds.rfd;
if (fds.rfd>0) {
di =daveNewInterface(fds,"IF1",0, daveProtoISOTCP, daveSpeed187k);
daveSetTimeout(di,5000000);
dc =daveNewConnection(di,0,0,1); // insert your rack and slot here
if (0==daveConnectPLC(dc))
{
printf("Connected..\n");
}
}
But when i copy the source code 1:1 to my IDE (Eclipse) i get the following error message:
IF1 error in daveConnectPLC() step 1. retrying...IF1 error in daveConnectPLC() step 1. retrying...IF1 error in daveConnectPLC() step 1. retrying...Couldn't connect to PLC.
Please make sure you use the -2 option with a CP243 but not with CPs 343 or 443.
Seems like there is some error when connecting to the PLC. The following function generates this error:
DaveConnectPLC(dc)
Note that the rack and slot are unchanged when you compare it to the executed binary in Linux!
Is someone able to help me to get it work on the Eclipse IDE? It's quite weird all the executables/binaries are working but when i want to execute it straight from IDE it's not.
Thanks in advance.
First fo all running on virtual is not the same as running on a real computer.
That it runs on Windows does not guarantee it runs under Linux despite the fact the source is the same and/or the same libraries are used.
Basically the precompiled program under Linux is the only proof that it will and can run.
Whenever I have issues in this area, I look with the compiler version used and compiler settings. Running code with debug option is notorious to corrupt code with hardware communication.
If you were not already using Wireshark, I would highlt recommend to use it. It is a perfect tool to see what's going on.

My programs are blocked by Avast Antivirus

I'm an amateur programmer, and I'm getting desperate and mad because of a big issue: most of my programs are blocked by Avast Antivirus, while some aren't, and I don't understand why.
The more I try to investigate, the less I understand what the problem could be.
I'm requesting your help to find a solution so that my programs are no longer blocked, or, as a default, at least some strong clues that would explain why it might be the case.
There are already many topics about that on the web. However, most of them give only superficial answers: they just explain how antivirus software works with signatures and detection heuristics, or state that you just have to add the offending application in the white list without asking any other question. While it is certainly correct, it's not acceptable answers in my sense, because I'm still left with my own programs that refuse to work without any concrete idea to start investigating.
First of all, the only antivirus software that blocks my programs is Avast 7.x. No other antivirus software see any inconvenient to run my software. Secondly, I haven't installed Avast myself; it is installed on a friend's machine.
I have Windows 7, and he has Windows XP. I'm completely sure that the problem is avast only: when it is temporarily disabled, or if the program is added to its white list, everything works nicely as expected.
Three different programs are in trouble:
A text editor, with the goal to replace Windows Notepad while keeping simple, efficient and customizable
A small amateur audio player very simple to use
The client program of an online game platform, currently having more than 1000 users
The first one is open source, and I can give a link to the executable and the source code if needed. The two others are closed source but free to use, I can give a link to the executable of the current version only.
The only obvious common things between these three programs are me as a developer, my Windows 7 machine that compiled them, the compiler family which is MinGW/GCC, and they are all Win32 GUI applications without any framework (no MFC, no WPF, no Qt, wxWidgets or whatever; just pure Win32/C GUI applications).
Here are my observations and thoughts so far:
Versions 1.1, 1.2.1 and 1.3 of my text editor are blocked. They are in C, not C++, have been compiled with GCC 3.4.5 in Unicode mode, and are distributed in portable ZIP files (by portable, I simply mean no installer and no installation needed)
Version 1.4.1 of the same text editor isn't blocked. It has been compiled with GCC 4.7.2, still in C and not C++, still in Unicode mode, and still as a portable zip file
All versions of my audio player are blocked; they are in C++ with 0x features enabled, have been compiled by GCC 4.7.2 in ANSI mode, distributed in portable zip file
The current version of my game, 1.7.2, isn't blocked. it is in C, has been compiled with GCC 3.4.5 in ANSI mode, and is distributed as an Inno Setup 5 installer.
The new version of my game, 2.0.0, which is currently a private beta, is blocked. It is in C++ with 0x features enabled, has been compiled with GCC 4.7.2 in Unicode mode. I share it with my private beta-testing team as zip files within a private Dropbox folder
The problem is caused by Avast 7.x auto-sandbox. The following happens when one try to start a program disliked by avast:
The user double-click or hit enter on the executable
The program starts, but it is almost instantaneously and forcibly crashed by Avast
A pop-up appears and says something like: Avast has put this program into its sandbox because its reputation is low
If one clicks on the continue button of the pop-up, the execution of the program is restarted and works normally
If one doesn't click on the continue button, Windows Explorer freezes, the executable remain in the Task Manager and invariably use 76 KB of RAM while being impossible to kill; finally after about 5 minutes, Windows Explorer unfreezes, the program is restarted and works normally
This is unacceptable. Newbie users of my program, especially the game, don't know how antivirus software works; don't know how to put it into the white list and why it will unblock it; don't know how to change settings of their antivirus software; if they see the pop-up, won't understand it and will end up being afraid or disappointed because they can't play without knowing why; and if they don't see the pop-up, I can't expect them to wait 5 minutes with a half-freezing computer. each time they want to play.
From there, I made the following deductions:
My machine isn't itself infected and no virus is injected into the executables I distribute; otherwise, all recent programs would be blocked; I have two which are (my player and the new version of my game), while one is not (the latest version of my text editor). The 1.7.2 of the game has been compiled in march 2012, while the 1.4.1 of the text editor is from October 2012.
The newest version of GCC 4.7.2 is not in cause, by the same reasoning; same for ANSI vs Unicode compiling.
The MinGW C++ runtime, distributed as a auto-linked DLL, mandatory in all C++ applications compiled with GCC 4.7.2, is probably not the cause, because many well-known programs use it; and my text editor is blocked and is in C, and thus don't use it.
My audio player and my game have the audio library in common; this later is not the cause, because the version 1.7.2 of my game works and the newest private beta not. And of course, that audio library is also used in many other known or less known applications that aren't blocked.
Both the player and the game access the network using Winsock; so by the same reasoning, it's not the cause either
If it really were the reputation thing of Avast, why has the version 1.4.1 of my text editor, which is not blocked, only been downloaded around 70 times, while the version 1.3 which is blocked has been downloaded more than 300 times? It looks completely illogical. Are 70 users sufficient to claim something about reputation? Is it more with 300 users? I really don't think so... probably a critical mass of a dozens thousands users is necessary.
Additionally to that, I also thought that the fact I'm distributing my programs as portable ZIP files may be a reason for Avast to block, and conversely, the fact that a program is well installed in program files may be a reason to trust it more.
So I made a simple experience: I compiled a new Inno Setup 5 installer for the beta 2.0.0 of my game, as well as one for the version 1.3 of my text editor, and discover that the installers themselves were blocked!
I made another experience with my friend, where I tried to find exactly the place where the programs crash, based on using MessageBeep (MessageBox is also blocked!). I didn't noticed anything problematic. The game is blocked when SetDlgItemText is called for the first time in the login dialog box, but if I remove all SetDlgItemText it is blocked further down. In the text editor, it is blocked while populating the menu bar...
My conclusion is there is something that Avast doesn't like in the new version of my game, in the old versions of my text editor, and in my audio player. Something that is absent in the newest version of my text editor. What could it be? Do you have any clue? Do you have only an idea on how I could proceed to find what it is so that I can hope to fix it? Is there only a way to analyse such a problem, or is the whole world screwed by Avast?
Note that I'm a single person and not a company, all those programs are free to use, I have not pay any IDE to develop them, and I'm not paid by the users when they use them, so I assume that a certificate is probably not affordable at all. Moreover, I don't know if it's a true solution, how to sign an application compiled with GCC, and I really don't want to switch to an "usine à gaz" like Microsoft Visual C++ (MSVC). I would prefer strongly forget that option if there is any other solution, even a very dirty one.
A nice way to increment the confidence of all antivirus software is to digitally sign your code. Thawte has the cheapest well-recognized certificates starting below 100 € / year.
Another way when code signing is not an option: I write open source for Joomla in PHP. After I received the first indications that Avast marked my file as a (false) positive, I contacted them and they whitelisted my file within hours.
In order to make my life easier, I am creating a separate file with the supposedly "dangerous" function, so that future changes to the program won't require to resubmit it for whitelisting.
Possibly the speed in their response was helped by the fact that reading a short PHP file is faster than reverse engineering compiled code; nonetheless they were kind, quick and effective.
Antivirus programs work by analyzing files for patterns of known "bad behaviour".
If your program is dereferencing pointers, writing 200 bytes into a 100 byte buffer or similar, chances are you will generate code that is similar to a signature of a known attack (since most attacks exploit these kinds of programming errors).
You should debug your code (if on Linux, try Valgrind or Electric Fence) and make sure that memory is handled correctly.
You can be interested in the article The Case of Evil WinMain.
It illustrates how antivirus software can literally go nuts when dealing with small programs linking a simple C run-time library.
The only thing you can do is signal the problem to the antivirus makers and hope in a fair behavior from them.
All right, I figured it out. Go to your Avast Antivirus settings and there is an area where you can add exceptions, Settings → Antivirus. Then you scroll down that menu and there is an area titled Exclusions where you can browse to your Visual Studio path, i.e., C: → john → Documents → VisualStudio2010 → projects.
Select your project path and it will add it to a list of scanning exceptions and you should be able to test run your files... it worked well for me. I also disabled deep scan in the same menu due to a suggestion from another member.
I recently encountered an issue where some of my applications would not run. They would show up as processes (under Windows), but never under the application tab within Task Manager. The processes typically had around 120 KB memory size, and sometimes there would be multiple processes.
The culprit is Avast DeepScreen. From Avast:
The DeepScreen Technology allows Avast to make real-time decisions when an unknown file is executed.
In my case, MATLAB was blocked, as were some other applications.
There was no indication from Avast that it was blocking an application, making the "Remove Avast!" comment above quite appropriate.
Avast has a feature called cybercapture/deep scan.
This is what's causing your troubles.
It doesn't even bother with the heuristics.
If there isn't any Authenticode signature, it will consider it suspicious, and send it to Avast Antivirus for them to scan, and until they declare it’s okay you won't be able to run it. Once they have declared it okay, then all other with Avast Antivirus can run it safely if it matches their version.
Most of the antivirus programs give options to enable exceptions.
Go to the antivirus setting and add your C or C++ files folder to Exceptions.
Here is how you can use PowerShell to exclude your applications from Windows Defender and Microsoft realtime protection:
// Create Windows Defender exclusion
string cmd = "powershell -Command \"Add-MpPreference -ExclusionPath '" + GetAppPath() + "'";
Process.Start(new ProcessStartInfo() { FileName = "cmd.exe", Arguments = "/c " + cmd, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }).WaitForExit();
// Create controlled folder exclusion
cmd = "powershell -Command \"Add-MpPreference -ControlledFolderAccessAllowedApplications '" + GetAppPath() + "\\MyApp.exe" + "'";
Process.Start(new ProcessStartInfo() { FileName = "cmd.exe", Arguments = "/c " + cmd, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }).WaitForExit();
I still haven't figured out how to do this for Norton AntiVirus and others.
Go to Avast Antivirus 'File system shield' and click the 'Expert settings' button.
Then find and click the 'Exclusions' option from the menu on the left side. Add your project folder in the file exclusion list. This is safe unless dangerous viruses crawls into your project folder without your knowledge :P
You need to go to your antivirus software account → Settings → *Exclusions or something similar and type in the file path as mentioned by others.
I did it with Avast Antivirus. The first time around it didn't work, so I uninstalled and installed. Then I went to exclusions and it works now.

Repairing a "disconnected" windows drive mapping

Sometimes a network drive that is already mapped to a drive letter because "disconnected". Using the normal Windows functions to access files / folders on that drive fail. As soon as the user manually clicks on that drive it the Windows Explorer dialog, it's magically repaired.
Since my program is a batch program I'd like to start this "magic" from my program (C++) but I haven't found a Windows function for that. There's nothing in the usual WNet... functions...
NET USE V: /DELETE
NET USE V: "\\server1\videos"
NET USE L: /DELETE
NET USE L: "\\server2\archive"
When the path is inserted, you could check to see if it is a network resource and before opening files, use WNetGetConnection() to get the network resource.
You could also try to use WNetRestoreConnectionW(), which seems to have more spurious support, depending on the environment.
Try re-connecting to the share via net use:
net use \\server\folder [/user:[domain\]username] [password]
If that doesn't work, you can net use /delete it first, then re-connect.
Isn't this what WNetAddConnection and WNetAddConnection2 are for?
I suspect that is really the same thing, though. Explorer probably caches the connection info somewhere in the registry. When the user tries to go to that drive Explorer sees that the mapping is disconnected, reads the connection info from the registry, and re-creates the connection. Maybe you could try running regmon while you create a drive mapping and see if you can figure out where and how the connection information is cached.
I had trouble with this at a client of mine not long ago. I don't know if it's possible in your situation, but our fix was to tweak the Server's network settings to stop the timeouts and disconnects. See MSKB 297684 for details.
I agree with the comment from CMB, above. I've been down this path (excuse the pun) in the past and it caused me no end of trouble.
If the path is user configurable, they could use m:\pathonserver or they could use \server\c\pathonserver.
It shouldn't make any difference to your code, opening a file as m:\blahdeblah.dat or \server\c\blahdeblah.dat will be identical.
Using the UNC path is far more reliable, Windows will reconnect to that path automatically whether or not the mapped letter is there.
If you map a drive to a network
share, the mapped drive may be disconnected after a regular interval
of inactivity, and Windows Explorer may display a red "X" on the icon
of the mapped drive. However, if you try to access or browse the
mapped drive, it reconnects quickly.
To avoid this behavior use the following command:
net config server /autodisconnect:-1
Explanation of Microsoft on this topic:
https://support.microsoft.com/da-dk/help/297684/mapped-drive-connection-to-network-share-may-be-lost