LDAP connection with AD using C++ - c++

I'm trying to just make an LDAP connection with Active directory to get the list of users. But I'm not even able to compile the simple code for just authentication with the AD using C++.
I have tried many C++ example programs but only got compilation errors. I really just want to connect with AD using C++ without any errors. So can you please tell me what I'm doing wrong in this code which attempts to add a new user to the AD. I have added the environment details, code and errors below for reference.
CODE:
#ifndef UNICODE
#define UNICODE
#endif
#pragma comment(lib, "netapi32.lib")
#include <windows.h>
#include <lm.h>
#include<iostream>
int main()
{
USER_INFO_1 ui;
DWORD dwLevel = 1;
DWORD dwError = 0;
NET_API_STATUS nStatus;
//
// Set up the USER_INFO_1 structure.
// USER_PRIV_USER: name identifies a user,
// rather than an administrator or a guest.
// UF_SCRIPT: required
//
ui.usri1_name = L"username";
ui.usri1_password = L"password";
ui.usri1_priv = USER_PRIV_USER;
ui.usri1_home_dir = NULL;
ui.usri1_comment = NULL;
ui.usri1_flags = UF_SCRIPT;
ui.usri1_script_path = NULL;
//
// Call the NetUserAdd function, specifying level 1.
//
nStatus = NetUserAdd(L"servername",
dwLevel,
(LPBYTE)&ui,
&dwError);
//
// If the call succeeds, inform the user.
//
if (nStatus == NERR_Success)
fwprintf(stderr, L"User %s has been successfully added on %s\n",
L"user", L"dc");
//
// Otherwise, print the system error.
//
else
fprintf(stderr, "A system error has occurred: %d\n", nStatus);
return 0;
}
ERROR:
PS C:\Users\user\Desktop\Sandbox\Cpp> cd "c:\Users\user\Desktop\Sandbox\Cpp\" ; if ($?) { g++ ldap.cpp -o ldap } ; if ($?) { .\ldap }
ldap.cpp: In function 'int main()':
ldap.cpp:22:20: warning: ISO C++ forbids converting a string constant to 'LPWSTR' {aka 'wchar_t*'} [-Wwrite-strings]
22 | ui.usri1_name = L"username";
| ^~~~~~~~~~~
ldap.cpp:23:24: warning: ISO C++ forbids converting a string constant to 'LPWSTR' {aka 'wchar_t*'} [-Wwrite-strings]
23 | ui.usri1_password = L"password";
| ^~~~~~~~~~~
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\user-1~1\AppData\Local\Temp\ccByZfCT.o:ldap.cpp:(.text+0xfb): undefined reference to `NetUserAdd'
collect2.exe: error: ld returned 1 exit status
My system run on Windows 10 64bit
Installed MSYS with MinGW64 compiler.

I'm no C++ or MinGW expert, but I have a little experience, and I did some Googling. This is the only error:
undefined reference to `NetUserAdd'
The others are warnings.
By your output, it looks like your command to compile is this:
g++ ldap.cpp -o ldap
Try adding -lnetapi32 to the end of that:
g++ ldap.cpp -o ldap -lnetapi32
If you want to resolve those warnings, I think you can declare variables for the username and password rather than assigning literals directly to the struct:
wchar_t username[] = L"username";
wchar_t password[] = L"password";
ui.usri1_name = username;
ui.usri1_password = password;

Related

Windows Sharing file over network NetShareAdd Error 53

I tried to compile this example from microsoft docs for sharing a folder over network however the executable gives an error.
Full Code :
#include "stdafx.h"
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#include <stdio.h>
#include <lm.h>
#pragma comment(lib, "Netapi32.lib")
void wmain(int argc, TCHAR *argv[])
{
NET_API_STATUS res;
SHARE_INFO_2 p;
DWORD parm_err = 0;
if (argc<2)
printf("Usage: NetShareAdd server\n");
else
{
//
// Fill in the SHARE_INFO_2 structure.
//
p.shi2_netname = TEXT("TESTSHARE");
p.shi2_type = STYPE_DISKTREE; // disk drive
p.shi2_remark = TEXT("TESTSHARE to test NetShareAdd");
p.shi2_permissions = 0;
p.shi2_max_uses = 4;
p.shi2_current_uses = 0;
p.shi2_path = TEXT("F:\\abc");
p.shi2_passwd = NULL; // no password
//
// Call the NetShareAdd function,
// specifying level 2.
//
res = NetShareAdd(argv[1], 2, (LPBYTE)&p, &parm_err);
//
// If the call succeeds, inform the user.
//
if (res == 0)
printf("Share created.\n");
// Otherwise, print an error,
// and identify the parameter in error.
//
else
printf("Error: %u\tparmerr=%u\n", res, parm_err);
}
return;
}
Exe command :
ConsoleApplication1.exe myShare
Error Shown :
Error: 53 parmerr=0
However the follwing from cmd works fine :
net share abc=F:\abc
I am unable to figure out what actually the error is and how to resolve that. can anybody help?
I am on windows 11 and code is compiled on VS 2015 Community.
With admin privileges, servername ConsoleApplication1.exe localhost and ConsoleApplication1.exe 127.0.0.1 worked fine.

ALSA in C++ - Making the minimal working code

Topic
I would like to make the minimal working code to generate any kind of PCM sound using ALSA in C++ for a Linux computer.
Setup
I'm coding in C++ on Code::Blocks with Ubuntu 20.04.
Background
I used to make simple Arduino UNO programs doing sound processing and just needed to play raw PCM samples.
Issues
ALSA Project's Website is not very easy to understand.
I looked at c - ALSA tutorial required to find out that many links are expired.
I copy pasted the code of the minimal PCM example in C directly into a empty Code::Blocks project and I got that error:
||=== Build: Release in Test (compiler: GNU GCC Compiler) ===|
Test/main.cpp|5|fatal error: ../include/asoundlib.h: No such file or directory|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
Right in the first line of code which is #include "../include/asoundlib.h".
I'm guessing that the issue could be because I have to download something or add a linker for the compiler.
But I also think it may be an issue of C to C++ conversion meaning that this works in C but not in C++.
Do I have to add a linker for the compiler or download something to make the code working?
Then I looked on ALSA library and downloaded alsa-lib-1.2.3.tar.bz2.
I got an archive that looked to have the right things but I don't know how to handle it.
Then I found usr/include/sound/asound.h on my computer. It looks to be part of ALSA but when I changed the code to use it, it spat out a bunch of errors when used.
The code looks like following now:
/*
* This extra small demo sends a random samples to your speakers.
*/
#include <sound/asound.h>
#include <cstdio>
static char *device = "default"; /* playback device */
unsigned char buffer[16*1024]; /* some random data */
int main(void)
{
int err;
unsigned int i;
snd_pcm_t *handle;
snd_pcm_sframes_t frames;
for (i = 0; i < sizeof(buffer); i++)
buffer[i] = random() & 0xff;
if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
printf("Playback open error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
if ((err = snd_pcm_set_params(handle,
SND_PCM_FORMAT_U8,
SND_PCM_ACCESS_RW_INTERLEAVED,
1,
48000,
1,
500000)) < 0) { /* 0.5sec */
printf("Playback open error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
for (i = 0; i < 16; i++) {
frames = snd_pcm_writei(handle, buffer, sizeof(buffer));
if (frames < 0)
frames = snd_pcm_recover(handle, frames, 0);
if (frames < 0) {
printf("snd_pcm_writei failed: %s\n", snd_strerror(frames));
break;
}
if (frames > 0 && frames < (long)sizeof(buffer))
printf("Short write (expected %li, wrote %li)\n", (long)sizeof(buffer), frames);
}
/* pass the remaining samples, otherwise they're dropped in close */
err = snd_pcm_drain(handle);
if (err < 0)
printf("snd_pcm_drain failed: %s\n", snd_strerror(err));
snd_pcm_close(handle);
return 0;
}
And the errors are like that:
||=== Build: Release in Test (compiler: GNU GCC Compiler) ===|
Test/main.cpp|6|warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]|
Test/main.cpp||In function ‘int main()’:|
Test/main.cpp|12|error: ‘snd_pcm_t’ was not declared in this scope; did you mean ‘snd_pcm_info’?|
Test/main.cpp|12|error: ‘handle’ was not declared in this scope|
Test/main.cpp|16|error: ‘SND_PCM_STREAM_PLAYBACK’ was not declared in this scope; did you mean ‘SNDRV_PCM_STREAM_PLAYBACK’?|
Test/main.cpp|16|error: ‘snd_pcm_open’ was not declared in this scope; did you mean ‘snd_pcm_info’?|
Test/main.cpp|17|error: ‘snd_strerror’ was not declared in this scope|
||error: %s\n", snd_strerror(err));|
Test/main.cpp|21|error: ‘SND_PCM_FORMAT_U8’ was not declared in this scope; did you mean ‘SNDRV_PCM_FORMAT_U8’?|
Test/main.cpp|22|error: ‘SND_PCM_ACCESS_RW_INTERLEAVED’ was not declared in this scope; did you mean ‘SNDRV_PCM_ACCESS_RW_INTERLEAVED’?|
Test/main.cpp|20|error: ‘snd_pcm_set_params’ was not declared in this scope; did you mean ‘snd_pcm_sw_params’?|
Test/main.cpp|27|error: ‘snd_strerror’ was not declared in this scope|
||error: %s\n", snd_strerror(err));|
Test/main.cpp|31|error: ‘snd_pcm_writei’ was not declared in this scope|
Test/main.cpp|33|error: ‘snd_pcm_recover’ was not declared in this scope|
Test/main.cpp|35|error: ‘snd_strerror’ was not declared in this scope|
Test/main.cpp|42|error: ‘snd_pcm_drain’ was not declared in this scope|
Test/main.cpp|44|error: ‘snd_strerror’ was not declared in this scope|
Test/main.cpp|45|error: ‘snd_pcm_close’ was not declared in this scope|
||=== Build failed: 17 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
Follow these steps:
Install the ALSA development package, or make sure it is already installed. The name depends on your distribution. In my case (OpenSUSE Tumbleweed) it is alsa-devel. This will install the file asoundlib.h under the directory /usr/include/alsa.
Change the line in your code from #include "../include/asoundlib.h" to #include <alsa/asoundlib.h>. Notice the angular brackets instead of quotation marks.
The library which you want to link against is named libsound.so, so compile the program with a command like gcc -Wall pcm_min.c -lasound -o pcm_min
Run the program: ./pcm_min

error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive] in the given set of commands

I have c++ file like below one,
#include <iostream>
using namespace std;
extern "C" {
#include "sample_publish.c"
}
int main()
{
int antenna_id = 123;
send_message_to_mqtt(&antenna_id);
}
I have included a c file in c++ file and I need to pass the variable antenna_id to the function send_message_to_mqtt and the same is in c file like below one.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
void send_message_to_mqtt(int *antenna_id) {
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
MQTTClient_create(&client, "tcp://mqtt1.mindlogic.com:1883", "ExampleClientPub",
MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("DATA FROM C++:::%d\n", *antenna_id);
char payload_data[] = "hi";
//pubmsg.payload = payload_data;
pubmsg.payload = *antenna_id
pubmsg.payloadlen = (int)strlen(*antenna_id);
pubmsg.qos = 1;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, "MQTT-Examples", &pubmsg, &token);
printf("Waiting for up to %d seconds for publication of %s\n""on topic %s for client with ClientID: %s\n",(int)(10000L/1000), "Hello World!", "MQTT-Examples", "ExampleClientPub");
rc = MQTTClient_waitForCompletion(client, token, 10000L);
printf("Message with delivery token %d delivered\n", token);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
// return rc;
}
When I execute a c++ file, the antenna_id variable is doesnt accessible in c file which in turn not allowing me to map against pubmsg.payload and this is due to the below error,
dell#dell-Inspiron-5379:~/workspace_folder$ g++ sample.cpp -o sample -lpaho-mqtt3c
In file included from sample.cpp:5:0:
sample_publish.c: In function ‘void send_message_to_mqtt(int*)’:
sample_publish.c:30:22: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive]
pubmsg.payload = *antenna_id
^~~~~~~~~~~
sample_publish.c:31:5: error: expected ‘;’ before ‘pubmsg’
pubmsg.payloadlen = (int)strlen(*antenna_id);
^~~~~~
How to overcome this one?
A guess on the problem, it's most likely this line:
pubmsg.payload = *antenna_id
Besides missing the semicolon, the payload is a pointer to the first byte of the data to be sent. That is, you should not dereference the pointer:
pubmsg.payload = antenna_id;
On a related note, this line is also very wrong:
pubmsg.payloadlen = (int)strlen(*antenna_id);
The strlen function is to get the length if a null-terminate byte string.
The length of an int can be gotten with the sizeof operator:
pubmsg.payloadlen = sizeof *antenna_id;
Note that here you must use the dereference operator, otherwise you get the size of the pointer itself.

Undefined reference to 'getcwd' and 'mkdir' when building Google test project

even if I have been strictly following the tutorials from this post, I can't get my google test demo program to compile.
I'm using Eclipse on Windows 10 x64, and the ARM GCC embedded toolchain to compile my code, since I will eventually need to run unit tests on embedded devices.
My problem is that when I try to Build the project I get those errors :
c:/program files (x86)/gnu tools arm embedded/9 2019-q4-major/bin/../lib/gcc/arm-none-eabi/9.2.1/../../../../arm-none-eabi/bin/ld.exe: ./contrib/gtest/gtest-all.o: in function `testing::internal::FilePath::GetCurrentDir()':
C:\Users\Hugo\eclipse\eclipse-workspace\test_gtest\Debug/../contrib/gtest/gtest-all.cc:9598: undefined reference to `getcwd'
c:/program files (x86)/gnu tools arm embedded/9 2019-q4-major/bin/../lib/gcc/arm-none-eabi/9.2.1/../../../../arm-none-eabi/bin/ld.exe: ./contrib/gtest/gtest-all.o: in function `testing::internal::FilePath::CreateFolder() const':
C:\Users\Hugo\eclipse\eclipse-workspace\test_gtest\Debug/../contrib/gtest/gtest-all.cc:9823: undefined reference to `mkdir'
collect2.exe: error: ld returned 1 exit status
make: *** [makefile:61: test_gtest.elf] Error 1
It comes more precisely from those lines of code in the gtest_all.cc file:
For the undefined reference to 'getcwd'
FilePath FilePath::GetCurrentDir() {
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32
// These platforms do not have a current directory, so we just return
// something reasonable.
return FilePath(kCurrentDirectoryString);
#elif GTEST_OS_WINDOWS
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
#else
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
char* result = getcwd(cwd, sizeof(cwd));
# if GTEST_OS_NACL
// getcwd will likely fail in NaCl due to the sandbox, so return something
// reasonable. The user may have provided a shim implementation for getcwd,
// however, so fallback only when failure is detected.
return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
# endif // GTEST_OS_NACL
return FilePath(result == nullptr ? "" : cwd);
#endif // GTEST_OS_WINDOWS_MOBILE
}
For the undefined reference to 'mkdir' :
bool FilePath::CreateFolder() const {
#if GTEST_OS_WINDOWS_MOBILE
FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
delete [] unicode;
#elif GTEST_OS_WINDOWS
int result = _mkdir(pathname_.c_str());
#elif GTEST_OS_ESP8266
// do nothing
int result = 0;
#else
int result = mkdir(pathname_.c_str(), 0777);
#endif // GTEST_OS_WINDOWS_MOBILE
if (result == -1) {
return this->DirectoryExists(); // An error is OK if the directory exists.
}
return true; // No error.
}
I have checked that unistd.h was included. I've been searching a lot but can't seem to find any similar error as mine. The closest I could find has been solved by people using CMake to compile it, but I'm not using CMake at all here.
AFAIK, getcwd() and mkdir() is platform dependent.
It seem there have been similar issue with other library:
https://github.com/purduesigbots/pros/issues/176
As above link, you can try to define stub for missing symbols.
In my working platform, getcwd() and mkdir() even get removed from the header.
In such case, you can edit gtest directly, for example:
FilePath FilePath::GetCurrentDir() {
#if GTEST_OS_CUSTOM_PLATFORM
return kCurrentDirectoryString;
...

How to share a directory using C++ so everyone can access

I'm trying to make a program so that when it run, it will create a new folder on C://. I also want to add a feature where the folder can have a shared permission to everyone. So, everyone can access and read/write
I've tried using netshareadd but I always got a compiler warning, how do I get rid of it?
This is creating new directory code :
#include <direct.h>
int main()
{
mkdir("c:/scan");
return 0;
}
This is the netshareadd code :
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#include <stdio.h>
#include <lm.h>
#pragma comment(lib, "Netapi32.lib")
void wmain( int argc, TCHAR *argv[ ])
{
NET_API_STATUS res;
SHARE_INFO_2 p;
DWORD parm_err = 0;
if(argc<2)
printf("Usage: NetShareAdd server\n");
else
{
//
// Fill in the SHARE_INFO_2 structure.
//
p.shi2_netname = TEXT("TESTSHARE");
p.shi2_type = STYPE_DISKTREE; // disk drive
p.shi2_remark = TEXT("TESTSHARE to test NetShareAdd");
p.shi2_permissions = 0;
p.shi2_max_uses = 4;
p.shi2_current_uses = 0;
p.shi2_path = TEXT("C:\\scan");
p.shi2_passwd = NULL; // no password
//
// Call the NetShareAdd function,
// specifying level 2.
//
res=NetShareAdd(argv[1], 2, (LPBYTE) &p, &parm_err);
//
// If the call succeeds, inform the user.
//
if(res==0)
printf("Share created.\n");
// Otherwise, print an error,
// and identify the parameter in error.
//
else
printf("Error: %u\tparmerr=%u\n", res, parm_err);
}
return;
}
22 22 D:\kerja\NETSHARE.cpp [Warning] deprecated conversion from
string constant to 'LPWSTR {aka wchar_t*}' [-Wwrite-strings]
This is the warning that I always got when compiling the netshareadd code
NetShareAdd requires a non const parameter. Some Windows APIs modify the passed buffer (or are way old) so you need a wchar_t*, not a const wchar_t* which is what a L"string" produces.
Solution, copy the const wchar_t* into a vector and pass the vector's data() member to the function (don't forget the null terminator).