How to create own sysctl parameter - c

At version 4.10.0-38-generic there are no ctl_name field at ctl_table struct
I have found the tutorial https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=2ahUKEwie4Zz_5ZrdAhVKiaYKHRqsDiwQFjABegQICRAC&url=https%3A%2F%2Fsar.informatik.hu-berlin.de%2Fteaching%2F2012-s%2F2012-s%2520Operating%2520Systems%2520Principles%2Flab%2Flab-1%2Fsysctl_.pdf&usg=AOvVaw0mJdbT9E3lP2k3AQOGgzQz
But there are the usage of this field
Could you please give me an example of the usage of ctl_table at version 4.10.0-38-generic
I try to implement:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sysctl.h>
#define SUCCESS (0)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kasparyants George");
MODULE_DESCRIPTION("A simple Linux driver");
MODULE_VERSION("0.1");
static int global_var1 = 1;
static int global_var2 = 1;
static int min_val = 0;
static int max_val = 5;
static struct ctl_table_header* header;
static struct ctl_table child_ctl_table[] = {
{
.procname = "sample_value1",
.data = &global_var1,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.extra1 = &min_val,
.extra2 = &max_val
},
{
.procname = "sample_value2",
.data = &global_var2,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.extra1 = &min_val,
.extra2 = &max_val
},
{}
};
static struct ctl_table parent_ctl_table[] = {
{
.procname = "mykernel",
.mode = 0555,
.child = child_ctl_table
},
{}
};
static int __init sysctl_module_init(void) {
if (!(header = register_sysctl_table(parent_ctl_table))) {
printk(KERN_ALERT "Error: Failed to register parent_ctl_table\n");
return -EFAULT;
}
printk(KERN_INFO "Start global_var1 = %d, global_var2 = %d\n", global_var1, global_var2);
return SUCCESS;
}
static void __exit sysctl_module_exit(void) {
printk(KERN_INFO "End global_var1 = %d, global_var2 = %d\n", global_var1, global_var2);
}
module_init(sysctl_module_init);
module_exit(sysctl_module_exit);
But there are faults from time to time.
Also, i have another question:
At kernel sources, there is the comment, that this parameter is deprecated... Why?
How can I work with the hierarchy of parameters without this field?
Please help!

Fixed my bug
We should unregister_ctl_table in exit function
But also there is a question with the field "child"...

Related

after using rmmod program freezes

I have some problem with my code. In my code i solve the reader writers problem using RCU, when i load the module (insmod) everything works ok, and it works as i expected, but when i unload module (rmmod) my program freezes and I have to restart Ubuntu. In this program i have to use call_rcu() to delete previous version of the shared resource and i think that problem is here, because if i have not if I do not use this function and simply delete via kmalloc () then the program works as it should
#include<linux/module.h>
#include<linux/kthread.h>
#include<linux/wait.h>
#include<linux/slab.h>
#include<linux/rcupdate.h>
enum thread_index {WAKING_THREAD, WRITER_THREAD, FIRST_READER_THREAD, SECOND_READER_THREAD};
static struct thread_structure
{
struct task_struct *thread[4];
} threads;
struct st
{
int number;
struct rcu_head rcu;
};
static wait_queue_head_t wait_queue;
static bool condition;
static struct st *number_pointer = NULL;
static const int first_reader_number = 1, second_thread_number = 2;
static int reader_thread(void *data)
{
struct st *local_number_pointer = NULL;
for(;;) {
rcu_read_lock();
local_number_pointer = rcu_dereference(number_pointer);
if(local_number_pointer)
pr_info("[reader_number: %d] Value of \"number\" variable: %d\n",
*(int *)data,local_number_pointer->number);
rcu_read_unlock();
if(kthread_should_stop())
return 0;
set_current_state(TASK_INTERRUPTIBLE);
if(schedule_timeout(HZ>>2))
pr_info("Signal received!\n");
}
}
static void remove(struct rcu_head *x)
{
struct st *pntr = container_of(x, struct st, rcu);
kfree(pntr);
}
static int writer_thread(void *data)
{
struct st *local_number_pointer = NULL;
int number = 0;
DEFINE_WAIT(wait);
for(;;) {
struct st *old_pointer = NULL;
local_number_pointer = kmalloc(sizeof(*local_number_pointer),GFP_KERNEL);
if(IS_ERR(local_number_pointer)) {
pr_alert("Error allocating memory: %ld\n",PTR_ERR(local_number_pointer));
return 0;
}
local_number_pointer->number = number++;
old_pointer = number_pointer;
rcu_assign_pointer(number_pointer,local_number_pointer);
synchronize_rcu();
if(old_pointer)
call_rcu(&old_pointer->rcu, remove);
add_wait_queue(&wait_queue,&wait);
while(!condition) {
prepare_to_wait(&wait_queue,&wait,TASK_INTERRUPTIBLE);
if(kthread_should_stop())
return 0;
pr_info("[writer_thread]: awake\n");
schedule();
}
condition=false;
finish_wait(&wait_queue,&wait);
}
}
static int waking_thread(void *data)
{
for(;;) {
if(kthread_should_stop())
return 0;
set_current_state(TASK_INTERRUPTIBLE);
if(schedule_timeout(HZ))
pr_info("Signal received!\n");
condition=true;
wake_up(&wait_queue);
}
}
static int __init threads_init(void)
{
init_waitqueue_head(&wait_queue);
threads.thread[WRITER_THREAD] = kthread_run(writer_thread,NULL,"writer_thread");
threads.thread[WAKING_THREAD] = kthread_run(waking_thread,NULL,"waking_thread");
threads.thread[FIRST_READER_THREAD] =
kthread_run(reader_thread,(void *)&first_reader_number,"first_reader_thread");
threads.thread[SECOND_READER_THREAD] =
kthread_run(reader_thread,(void *)&second_thread_number,"second_reader_thread");
return 0;
}
static void __exit threads_exit(void)
{
kthread_stop(threads.thread[WAKING_THREAD]);
kthread_stop(threads.thread[WRITER_THREAD]);
kthread_stop(threads.thread[FIRST_READER_THREAD]);
kthread_stop(threads.thread[SECOND_READER_THREAD]);
}
module_init(threads_init);
module_exit(threads_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("An example of using the kernel linux threads and an RCU mechanism.");
MODULE_AUTHOR("Arkadiusz Chrobot <a.chrobot#tu.kielce.pl>");

How to insert a ramfs module into linux kernel

I want to compile source code of a very simple file system--ramfs. But when I inserted the module into Linux kernel 3.10 I got a problem:
could not insert module myramfs.ko: Device or resource busy
I don't know which step I did wrong。The following is my code.
source code:ramfs
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <linux/time.h>
#include <linux/string.h>
#include <linux/backing-dev.h>
#include <linux/ramfs.h>
#include <linux/sched.h>
#include <linux/parser.h>
#include <linux/magic.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#define RAMFS_DEFAULT_MODE 0755
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/ramfs.h>
const struct address_space_operations ramfs_aops = {
.readpage = simple_readpage,
.write_begin = simple_write_begin,
.write_end = simple_write_end,
.set_page_dirty = __set_page_dirty_no_writeback,
};
const struct file_operations ramfs_file_operations = {
.read = do_sync_read,
.aio_read = generic_file_aio_read,
.write = do_sync_write,
.aio_write = generic_file_aio_write,
.mmap = generic_file_mmap,
.fsync = noop_fsync,
.splice_read = generic_file_splice_read,
.splice_write = generic_file_splice_write,
.llseek = generic_file_llseek,
};
const struct inode_operations ramfs_file_inode_operations = {
.setattr = simple_setattr,
.getattr = simple_getattr,
};
static const struct super_operations ramfs_ops;
static const struct inode_operations ramfs_dir_inode_operations;
static struct backing_dev_info ramfs_backing_dev_info = {
.name = "ramfs",
.ra_pages = 0, /* No readahead */
.capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK |
BDI_CAP_MAP_DIRECT | BDI_CAP_MAP_COPY |
BDI_CAP_READ_MAP | BDI_CAP_WRITE_MAP | BDI_CAP_EXEC_MAP,
};
struct inode *ramfs_get_inode(struct super_block *sb,
const struct inode *dir, umode_t mode, dev_t dev)
{
struct inode * inode = new_inode(sb);
if (inode) {
inode->i_ino = get_next_ino();
inode_init_owner(inode, dir, mode);
inode->i_mapping->a_ops = &ramfs_aops;
inode->i_mapping->backing_dev_info = &ramfs_backing_dev_info;
mapping_set_gfp_mask(inode->i_mapping, GFP_HIGHUSER);
mapping_set_unevictable(inode->i_mapping);
inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
switch (mode & S_IFMT) {
default:
init_special_inode(inode, mode, dev);
break;
case S_IFREG:
inode->i_op = &ramfs_file_inode_operations;
inode->i_fop = &ramfs_file_operations;
break;
case S_IFDIR:
inode->i_op = &ramfs_dir_inode_operations;
inode->i_fop = &simple_dir_operations;
/* directory inodes start off with i_nlink == 2 (for "." entry) */
inc_nlink(inode);
break;
case S_IFLNK:
inode->i_op = &page_symlink_inode_operations;
break;
}
}
return inode;
}
/*
* File creation. Allocate an inode, and we're done..
*/
/* SMP-safe */
static int
ramfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
{
struct inode * inode = ramfs_get_inode(dir->i_sb, dir, mode, dev);
int error = -ENOSPC;
if (inode) {
d_instantiate(dentry, inode);
dget(dentry); /* Extra count - pin the dentry in core */
error = 0;
dir->i_mtime = dir->i_ctime = CURRENT_TIME;
}
return error;
}
static int ramfs_mkdir(struct inode * dir, struct dentry * dentry, umode_t mode)
{
int retval = ramfs_mknod(dir, dentry, mode | S_IFDIR, 0);
if (!retval)
inc_nlink(dir);
return retval;
}
static int ramfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool excl)
{
return ramfs_mknod(dir, dentry, mode | S_IFREG, 0);
}
static int ramfs_symlink(struct inode * dir, struct dentry *dentry, const char * symname)
{
struct inode *inode;
int error = -ENOSPC;
inode = ramfs_get_inode(dir->i_sb, dir, S_IFLNK|S_IRWXUGO, 0);
if (inode) {
int l = strlen(symname)+1;
error = page_symlink(inode, symname, l);
if (!error) {
d_instantiate(dentry, inode);
dget(dentry);
dir->i_mtime = dir->i_ctime = CURRENT_TIME;
} else
iput(inode);
}
return error;
}
static const struct inode_operations ramfs_dir_inode_operations = {
.create = ramfs_create,
.lookup = simple_lookup,
.link = simple_link,
.unlink = simple_unlink,
.symlink = ramfs_symlink,
.mkdir = ramfs_mkdir,
.rmdir = simple_rmdir,
.mknod = ramfs_mknod,
.rename = simple_rename,
};
static const struct super_operations ramfs_ops = {
.statfs = simple_statfs,
.drop_inode = generic_delete_inode,
.show_options = generic_show_options,
};
struct ramfs_mount_opts {
umode_t mode;
};
enum {
Opt_mode,
Opt_err
};
static const match_table_t tokens = {
{Opt_mode, "mode=%o"},
{Opt_err, NULL}
};
struct ramfs_fs_info {
struct ramfs_mount_opts mount_opts;
};
static int ramfs_parse_options(char *data, struct ramfs_mount_opts *opts)
{
substring_t args[MAX_OPT_ARGS];
int option;
int token;
char *p;
opts->mode = RAMFS_DEFAULT_MODE;
while ((p = strsep(&data, ",")) != NULL) {
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_mode:
if (match_octal(&args[0], &option))
return -EINVAL;
opts->mode = option & S_IALLUGO;
break;
/*
* We might like to report bad mount options here;
* but traditionally ramfs has ignored all mount options,
* and as it is used as a !CONFIG_SHMEM simple substitute
* for tmpfs, better continue to ignore other mount options.
*/
}
}
return 0;
}
int ramfs_fill_super(struct super_block *sb, void *data, int silent)
{
struct ramfs_fs_info *fsi;
struct inode *inode;
int err;
save_mount_options(sb, data);
fsi = kzalloc(sizeof(struct ramfs_fs_info), GFP_KERNEL);
sb->s_fs_info = fsi;
if (!fsi)
return -ENOMEM;
err = ramfs_parse_options(data, &fsi->mount_opts);
if (err)
return err;
sb->s_maxbytes = MAX_LFS_FILESIZE;
sb->s_blocksize = PAGE_CACHE_SIZE;
sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
sb->s_magic = RAMFS_MAGIC;
sb->s_op = &ramfs_ops;
sb->s_time_gran = 1;
inode = ramfs_get_inode(sb, NULL, S_IFDIR | fsi->mount_opts.mode, 0);
sb->s_root = d_make_root(inode);
if (!sb->s_root)
return -ENOMEM;
return 0;
}
struct dentry *ramfs_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_nodev(fs_type, flags, data, ramfs_fill_super);
}
static struct dentry *rootfs_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_nodev(fs_type, flags|MS_NOUSER, data, ramfs_fill_super);
}
static void ramfs_kill_sb(struct super_block *sb)
{
kfree(sb->s_fs_info);
kill_litter_super(sb);
}
static struct file_system_type ramfs_fs_type = {
.name = "ramfs",
.mount = ramfs_mount,
.kill_sb = ramfs_kill_sb,
.fs_flags = FS_USERNS_MOUNT,
};
static struct file_system_type rootfs_fs_type = {
.name = "rootfs",
.mount = rootfs_mount,
.kill_sb = kill_litter_super,
};
int __init init_ramfs_fs(void)
{
return register_filesystem(&ramfs_fs_type);
}
module_init(init_ramfs_fs)
int __init init_rootfs(void)
{
int err;
err = bdi_init(&ramfs_backing_dev_info);
if (err)
return err;
err = register_filesystem(&rootfs_fs_type);
if (err)
bdi_destroy(&ramfs_backing_dev_info);
return err;
}
Makefile:
ifneq ($(KERNELRELEASE),)
obj-m := myramfs.o
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
clean:
rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions *.order *.symvers *.unsigned

Compile-errors: "creating array with negative size ('-0x00000000000000001')", "assignment of read-only location"

Hi I'm new to GoogleMock but not new to mocking (I've python experience).
For a C-code based interface we want to use Googlemock. Up to compiling everything goes smoothly. No problems with defining the C-based code:
mock-header-file
#include "gmock/gmock.h"
extern "C"
{
#include "interface/interfacetype.h"
}
struct HELPER
{
virtual ~HELPER() {}
virtual int interface_func( ID_ENUM_TYPE id, MY_STRUCT_TYPE *params) = 0;
};
struct INTERFACE_MOCK : public HELPER
{
MOCK_METHOD2( interface_func, int( ID_ENUM_TYPE id, MY_STRUCT_TYPE *params) );
};
extern INTERFACE_MOCK *mock_create_mock();
extern void mock_delete_mock();
mock-implementation:
#include mock.h
extern "C"
{
#include "interface/interfacetype.h"
}
INTERFACE_MOCK *interface_2_mock = NULL;
extern "C"
{
int interface_func( ID_ENUM_TYPE id, MY_STRUCT_TYPE *params )
{
return interface_2_mock->interface_func( id, params );
}
}
INTERFACE_MOCK *mock_create_mock()
{
if ( interface_2_mock == NULL )
{
interface_2_mock = new( INTERFACE_MOCK );
}
return interface_2_mock;
}
void mock_delete_mock()
{
delete interface_2_mock;
}
MY_STRUCT_TYPE is as follows:
typedef struct my_struct_tag
{
float value[196]
} MY_STRUCT_TYPE
unittest-code is as follows:
INTERFACE_MOCK *interface_2_mock;
class fixture : public ::testing::Test
{
protected:
virtual void SetUp()
{
interface_2_mock = mock_create_mock();
}
virtual void TearDown()
{
mock_delete_mock();
}
};
TEST_F( fixture, test_case )
{
MY_STRUCT_TYPE params;
int result = 0;
for ( int i=0; i<196; i++)
{
params.value[i] = 1.23;
}
// I'm only interested in checking that function is called,
// mocking the return-value and mocking 'params' which is an output-param
EXPECT_CALL( *interface_2_mock, interface_func( _, _ ) )
.Times(2)
.WillRepeatedly( DoAll( SetArgReferee<1>( &params ), return 0 ) ) );
// Call function_under_test which calls interface_func
result = function_under_test();
ASSERT_EQ( 0, result ) << "Return-value " << result << " not as expected"
}
When compiling this all goes well until the EXPECT_CALL line is compiled. There we have the following error which we do not understand:
Rebuilding "<target>.oppsparc" on host "<host>"
======== Finished "<target>.oppsparc" on host "<host>" ========
Sun native compile : test_my_test.cpp to test_my_test.oppsparc
In file included from ./gmock/gmock.h:65,
from mock/interface_2_mock.hpp:33,
from test_my_test.cpp:23:
./gmock/gmock-more-actions.h: In member function 'typename testing::internal::Function<F>::Result testing::SetArgRefereeActionP<k, value_type>::gmock_Impl<F>::gmock_PerformImpl(const typename testing::internal::Function<F>::ArgumentTuple&, arg0_type, arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, arg7_type, arg8_type, arg9_type) const [with arg0_type = ID_ENUM_TYPE , arg1_type = MY_STRUCT_TYPE*, arg2_type = testing::internal::ExcessiveArg, arg3_type = testing::internal::ExcessiveArg, arg4_type = testing::internal::ExcessiveArg, arg5_type = testing::internal::ExcessiveArg, arg6_type = testing::internal::ExcessiveArg, arg7_type = testing::internal::ExcessiveArg, arg8_type = testing::internal::ExcessiveArg, arg9_type = testing::internal::ExcessiveArg, F = void( ID_ENUM_TYPE , MY_STRUCT_TYPE*), int k = 1, value_type = MY_STRUCT_TYPE*]':
./gmock/gmock-generated-actions.h:664: instantiated from 'static Result testing::internal::ActionHelper<Result, Impl>::Perform(Impl*, const std::tr1::tuple<_U1, _U2>&) [with A0 = ID_ENUM_TYPE , A1 =MY_STRUCT_TYPE*, Result = void, Impl = testing::SetArgRefereeActionP<1, MY_STRUCT_TYPE*>::gmock_Impl<void( ID_ENUM_TYPE ,MY_STRUCT_TYPE*)>]'
./gmock/gmock-more-actions.h:170: instantiated from 'typename testing::internal::Function<F>::Result testing::SetArgRefereeActionP<k, value_type>::gmock_Impl<F>::Perform(const typename testing::internal::Function<F>::ArgumentTuple&) [with F = void( ID_ENUM_TYPE , MY_STRUCT_TYPE*), int k = 1, value_type = MY_STRUCT_TYPE*]'
test_my_test.cpp:251: instantiated from here
./gmock/gmock-more-actions.h:175: error: creating array with negative size ('-0x00000000000000001')
./gmock/gmock-more-actions.h:177: error: assignment of read-only location 'std::tr1::get [with int __i = 1, _Elements = ID_ENUM_TYPE, MY_STRUCT_TYPE*](((const std::tr1::tuple<ID_ENUM_TYPE, MY_STRUCT_TYPE*>&)((const std::tr1::tuple<ID_ENUM_TYPE, MY_STRUCT_TYPE*>*)args)))'
*** Error code 1
========================================================
Aborting...
Can you help us?
/* edit */ I saw that I left out the fixture
This time I found the answer. Instead of SetArgReferee<1>( &params ), I've should have used SetArgPointee<1>( params )

How to send single channel scan request to libnl, and receive single channel scan completion response for corresponding channel

I am sending single SSID and frequency to libnl for scanning, but i got multiple scan result along with my requested SSID and frequency,But i need single scan result (only for requested SSID), how to achieve this. Kindly help me , i am sending my code also.This code will run.
Compile: gcc -g -o scan scantesthandler.c -L /usr/lib/i386-linux-gnu/libnl.so -lnl
Run with debug log: NLCB=debug ./scan
#include<assert.h>
#include<errno.h>
#include<ifaddrs.h>
#include<netdb.h>
#include<stddef.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/socket.h>
#include <asm/types.h>
#include <linux/rtnetlink.h>
#include <netlink/netlink.h>
#include <netlink/msg.h>
#include <netlink/cache.h>
#include <netlink/socket.h>
#include <netlink/genl/genl.h>
#include <netlink/genl/ctrl.h>
#include <stdlib.h>
#include <netlink/genl/genl.h>
#include <netlink/genl/ctrl.h>
#include <netlink/route/link.h>
#include <linux/nl80211.h>
static int expectedId;
static int ifIndex;
struct wpa_scan_res
{
unsigned char bssid[6];
int freq;
};
static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
{
int *ret = arg;
*ret = err->error;
return NL_SKIP;
}
static int finish_handler(struct nl_msg *msg, void *arg)
{
int *ret = arg;
*ret = 0;
return NL_SKIP;
}
static int ack_handler(struct nl_msg *msg, void *arg)
{
int *err = arg;
*err = 0;
return NL_STOP;
}
static int bss_info_handler(struct nl_msg *msg, void *arg)
{
printf("\nFunction: %s, Line: %d\n",__FUNCTION__,__LINE__);
struct nlattr *tb[NL80211_ATTR_MAX + 1];
struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
struct nlattr *bss[NL80211_BSS_MAX + 1];
static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
[NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
[NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
[NL80211_BSS_TSF] = { .type = NLA_U64 },
[NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
[NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
[NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
[NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
[NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
[NL80211_BSS_STATUS] = { .type = NLA_U32 },
[NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
[NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
};
struct wpa_scan_res *r = NULL;
r = (struct wpa_scan_res*)malloc(sizeof(struct wpa_scan_res));
nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
genlmsg_attrlen(gnlh, 0), NULL);
if (!tb[NL80211_ATTR_BSS])
return NL_SKIP;
if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
bss_policy))
return NL_SKIP;
if (bss[NL80211_BSS_BSSID])
memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),6);
if (bss[NL80211_BSS_FREQUENCY])
r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
printf("\nFrequency: %d ,BSSID: %2x:%2x:%2x:%2x:%2x:%2x",r->freq,r->bssid[0],r->bssid[1],r->bssid[2],r->bssid[3],r->bssid[4],r->bssid[5]);
return NL_SKIP;
}
static struct nl_msg* nl80211_scan_common(uint8_t cmd, int expectedId)
{
const char* ssid = "amitssid";
int ret;
struct nl_msg *msg;
int err;
size_t i;
int flags = 0,ifIndex;
msg = nlmsg_alloc();
if (!msg)
return NULL;
// setup the message
if(NULL==genlmsg_put(msg, 0, 0, expectedId, 0, flags, cmd, 0))
{
printf("\nError return genlMsg_put\n");
}
else
{
printf("\nSuccess genlMsg_put\n");
}
ifIndex = if_nametoindex("wlan1");
if(nla_put_u32(msg, NL80211_ATTR_IFINDEX, ifIndex) < 0)
{
goto fail;
}
struct nl_msg *ssids = nlmsg_alloc();
if(nla_put(ssids, 1,strlen(ssid) ,ssid) <0)
{
nlmsg_free(ssids);
goto fail;
}
err = nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS,ssids);
nlmsg_free(ssids);
if (err < 0)
goto fail;
struct nl_msg *freqs = nlmsg_alloc();
if( nla_put_u32(freqs,1 ,2437) < 0) //amitssid
{
printf("\nnla_put_fail\n");
goto fail;
}
else
{
printf("\nnla_put_u32 pass\n");
}
//add message attributes
if(nla_put_nested(msg, NL80211_FREQUENCY_ATTR_FREQ,freqs) < 0)
{
printf("\nnla_put_nested failing:\n");
}
else
{
printf("\nnla_put_nested pass\n");
}
nlmsg_free(freqs);
if (err < 0)
goto fail;
return msg;
nla_put_failure:
printf("\nnla_put_failure\n");
nlmsg_free(msg);
return NULL;
fail:
nlmsg_free(msg);
return NULL;
}
int main(int argc, char** argv)
{
struct nl_msg *msg= NULL;
int ret = -1;
struct nl_cb *cb = NULL;
int err = -ENOMEM;
int returnvalue,getret;
int ifIndex, callbackret=-1;
struct nl_sock* sk = (void*)nl_handle_alloc();
if(sk == NULL)
{
printf("\nmemory error\n");
return;
}
cb = nl_cb_alloc(NL_CB_CUSTOM);
if(cb == NULL)
{
printf("\nfailed to allocate netlink callback\n");
}
enum nl80211_commands cmd;
if(genl_connect((void*)sk))
{
printf("\nConnected failed\n");
return;
}
//find the nl80211 driverID
expectedId = genl_ctrl_resolve((void*)sk, "nl80211");
if(expectedId < 0)
{
printf("\nnegative error code returned\n");
return;
}
else
{
printf("\ngenl_ctrl_resolve returned:%d\n",expectedId);
}
msg = nl80211_scan_common(NL80211_CMD_TRIGGER_SCAN, expectedId);
if (!msg)
{
printf("\nmsgbal:\n");
return -1;
}
err = nl_send_auto_complete((void*)sk, msg);
if (err < 0)
goto out;
else
{
printf("\nSent successfully\n");
}
err = 1;
nl_cb_err(cb,NL_CB_CUSTOM,error_handler,&err);
nl_cb_set(cb,NL_CB_FINISH,NL_CB_CUSTOM,finish_handler,&err);
nl_cb_set(cb,NL_CB_ACK,NL_CB_CUSTOM,ack_handler,&err);
callbackret = nl_cb_set(cb,NL_CB_VALID,NL_CB_CUSTOM,bss_info_handler,&err);
if(callbackret < 0)
{
printf("\n*************CallbackRet failed:***************** %d\n",callbackret);
}
else
{
printf("\n*************CallbackRet pass:***************** %d\n",callbackret);
}
returnvalue=nl_recvmsgs((void*)sk,cb);
printf("\n returnval:%d\n",returnvalue);
nlmsg_free(msg);
msg = NULL;
msg = nlmsg_alloc();
if (!msg)
return -1;
if(NULL==genlmsg_put(msg, 0, 0, expectedId, 0, NLM_F_DUMP, NL80211_CMD_GET_SCAN, 0))
{
printf("\nError return genlMsg_put\n");
}
else
{
printf("\nSuccess genlMsg_put\n");
}
ifIndex = if_nametoindex("wlan1");
printf("\nGet Scaninterface returned :%d\n",ifIndex);
nla_put_u32(msg,NL80211_ATTR_IFINDEX,ifIndex);
err = nl_send_auto_complete((void*)sk,msg);
if(err < 0) goto out;
err = 1;
getret= nl_recvmsgs((void*)sk,cb);
printf("\nGt Scan resultreturn:%d\n",getret);
out:
nlmsg_free(msg);
return err;
nla_put_failure:
printf("\nnla_put_failure\n");
nlmsg_free(msg);
return err;
}
You can just copy and paste this code on your system and run it.
As far as I know (and have seen) the scan command and result is dependent upon the vendor's device driver. One thing for certain there is no option to scan for a specific ssid; instead what you can do is to get all the scan result and loop through to check whether the ssid is in the list or not (wpa_supplicant uses this mechanism to match network configuration with scan result).
Now for the frequency, it should be possible to scan only a certain channel if the device driver has that functionality. But generally scan command scans all channel and returns the SSID (think your network-manager; it shows all the available SSID found for a scan command. which is essentially posted by device driver via cfg80211).

How do I filter FindFirstUrlCacheEntry()?

I have studied the documentation on MSDN, but it doesn't work for me, I am wondering what I'm doing wrong?
My code is as follows, I am trying to filter my IE cache, for example, to get only the cookies:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wininet.h>
int main(void) {
DWORD dwEntrySize;
DWORD dw;
LPCTSTR filter = "cookie:";
INTERNET_CACHE_ENTRY_INFO * entry;
DWORD MAX_CACHE_ENTRY_INFO_SIZE = 4096;
HANDLE hCacheDir;
int nCount=0;
BOOL ok = FALSE;
dwEntrySize = MAX_CACHE_ENTRY_INFO_SIZE;
entry = malloc(dwEntrySize);
entry->dwStructSize = dwEntrySize;
printf("Reading IE cache\n");
hCacheDir = FindFirstUrlCacheEntry(filter, entry, &dwEntrySize);
if ( hCacheDir ) {
printf("%ws\n", entry->lpszLocalFileName);
nCount++;
do {
dwEntrySize = MAX_CACHE_ENTRY_INFO_SIZE;
entry = malloc(dwEntrySize);
entry->dwStructSize = dwEntrySize;
ok = FindNextUrlCacheEntry(hCacheDir, entry, &dwEntrySize);
if (ok && entry->lpszLocalFileName != NULL) {
printf("%ws\n", entry->lpszLocalFileName);
nCount++;
}
} while ( ok );
printf("**** end cache, total count: %d\n", nCount);
}
else {
dw = GetLastError();
printf("error code: %d\n", dw);
}
free(entry);
FindCloseUrlCache(hCacheDir);
return 0;
}

Resources