How to properly handle file read/write errors in C? - python

I want to rewrite yEnc code to make it compilable on Win32 with Visual Studio 2008.
The issue is that yEnc uses unistd.h (UNIX) functions fcntl to check if a file is readable or writable. It is of course not compatible with MS Visual Studio.
Here's what I want to be remove:
static Bool writable(FILE *file)
{
int mode = fcntl(fileno(file),F_GETFL) & O_ACCMODE;
return (mode == O_WRONLY) || (mode == O_RDWR);
}
static Bool readable(FILE *file)
{
int mode = fcntl(fileno(file),F_GETFL) & O_ACCMODE;
return (mode == O_RDONLY) || (mode == O_RDWR);
}
And here is how it is called:
FILE* infile = PyFile_AsFile(Py_infile);
FILE* outfile = PyFile_AsFile(Py_outfile);
if(!readable(infile) || !writable(outfile) ) {
return PyErr_Format(PyExc_ValueError, "file objects not writeable/readable");
}
/* File stuff including */
fread(&read_buffer, 1, in_ind, infile);
if(ferror(infile) || ferror(outfile)) {
return PyErr_Format(PyExc_IOError, "I/O Error while encoding");
}
fputc(CR, outfile);
fputc(LF, outfile);
fflush(outfile);
/* End of file stuff */
Can someone help me converting this readable/writable check (with equivalent of try {} catch {} instead) ?
I believe it is easier to handle errors on file read/write than trying to know if a Windows file is readable/writable, because there doesn't seem to be simple Windows equivalents to fcntl/F_GETFL.
The solution doesn't seem complicated but as I'm new to C and Python, I don't want to take the risk of making a buggy exception handler.
Thanks for your help.

You don't have to convert it just install windows POSIX.
http://www.cygwin.com/

Finally, I think the following checks will be sufficient:
infile == NULL
outfile == NULL
fread != read_count
fwrite != write_count
ferror
This should be sufficient. Moreover, the file have been opened in Python first and I presume this file open has been tested for exceptions.

{
public string writepath;
public string readpath;
public string line;
public List<Reciepient> reciepients = new List<Reciepient>();//linking my ist from my rec class
public int index;
public Form1()
{
InitializeComponent();
writebutton.Enabled = false;//disables write button
}
public void createbutton_Click(object sender, EventArgs e)
{
writebutton.Enabled = true;//enables write button
folderBrowserDialog1.ShowDialog();//open folder browser
writepath = folderBrowserDialog1.SelectedPath+ #"\test.txt";//generate path
StreamWriter sw = new StreamWriter(writepath);//open new sw
textBox1.Text = writepath;//write path to textbox1
sw.Close();//close my sw
}
public void readbutton_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();//open my file browser
readpath = openFileDialog1.FileName;//grabbing file name
StreamReader sr = new StreamReader(readpath);//creating new sr
textBox2.Text = readpath;//putting readpath in textbox2
while(sr.Peek()!= -1)//will stop reading if noo more lines
{
line = sr.ReadLine();//tells to read lines listed
Console.WriteLine(line);
/*if (line.Length > 0)
continue; messing up!!
else
MessageBox.Show("Line Cannot be Read");
*/
string fname = line.Substring(0, 5);
string lname = line.Substring(6, 6);
int loccode = Int32.Parse(line.Substring(13, 1));
int wcode = Int32.Parse(line.Substring(15, 1));
double itemcost = double.Parse(line.Substring(17, 5));
int acode = Int32.Parse(line.Substring(23, 1));
Reciepient file = new Reciepient(fname, lname, loccode, wcode, itemcost,
acode);
reciepients.Add(file);//add to list
}
sr.Close();//closes streamreader
}
public void writebutton_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(writepath);
Console.WriteLine(reciepients.Count);
for (int index = 0; index < reciepients.Count(); index++)
{
Reciepient file = reciepients.ElementAt(index);
sw.WriteLine(file.fname + " " + file.lname +" "+ "="+ file.totalcost);
}
sw.Close();
}

Related

Creating a new timer_t object after deleting a previous one doesn't work

I'll try to keep it as short as possible.
I'm making a python application which uses a C Extension (hw_timer).
This extension is in charge of creating a timer.
The Python application starts by calling hw_timer.StartTimer which instantiates a timer object.
After that, inside an infinite loop, the Python keeps calling hw_timer.ResetTimer and hw_timer.StartTimer. Reset timer de facto destroys the timer and then a new one is created with StartTimer and so on.
The code went through several changes since, no matter what, I kept getting segmentation faults whenever I tried to create a new timer.
However the situation now is VERY strange.
Here's the Python code: you'll notice I've removed the infinite loop I described before because I wanted to create a very simple scenario to showcase my issue
if __name__ == "__main__":
timerPtr = hw_timer.StartTimer(os.getpid()) #start timer returns a tuple
print("timer,tid,pid -> {}".format(timerPtr))
print("Result of reset timer: {}".format(hw_timer.ResetTimer(timerPtr[0])))
print("---------")
time.sleep(10)
timerPtr=hw_timer.StartTimer(os.getpid())
print("timer,tid,pid -> {}".format(timerPtr))
print("Result of reset timer: {}".format(hw_timer.ResetTimer(timerPtr[0])))
print("---------")
time.sleep(10)
And this is the output
timer,tid,pid -> (16985424, 16598768, 45975)
Result of reset timer: (16985424, 16598768, 45975)
---------
timer,tid,pid -> (16598768, 15553760, 45975)
timer_delete: Invalid argument
As you can see, despite replicating the same code twice, the second time, system method time_delete fails during the computation of ResetTimer.
Now the following is the C code (I've removed as much Python.h related content as possible to make it more readable)
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
struct tmr_struct
{
timer_t* tid;
int pid;
};
typedef struct sigevent signal_event;
typedef struct tmr_struct tmr_data;
typedef struct itimerspec tmr_spec;
static const int TIMER_SECOND = 5;
//Method called after timer expiration
void signal_handler (int sv)
{
exit(1);
}
//Creation of a new timer_t object stored inside a tmr_data struct
static void _StartTimer(tmr_data* timer)
{
timer->tid = new timer_t();
signal_event sev;
signal(SIGUSR1, signal_handler);
sev.sigev_notify = SIGEV_THREAD_ID;
sev.sigev_notify_function = NULL;
sev._sigev_un._tid = timer->pid;
sev.sigev_signo = SIGUSR1;
sev.sigev_notify_attributes = NULL;
tmr_spec ts;
if (timer_create(CLOCK_REALTIME, &sev, timer->tid) == -1) {
perror("timer_create");
exit(1);
}
memset(&ts,0,sizeof(ts));
ts.it_value.tv_nsec = 0;
ts.it_value.tv_sec = TIMER_SECOND;
ts.it_interval.tv_nsec = 0;
ts.it_interval.tv_sec = 0;
if (timer_settime(*(timer->tid), 0, &ts, NULL) == -1) {
perror("timer_settime");
exit(1);
}
return;
}
//Start timer method called from the Python application
//Accepts the PID of the Python App and later passes it to _StartTimer using the tmr_data struct
static PyObject* StartTimer(PyObject* self, PyObject* args) {
int pid;
tmr_data* timer = new tmr_data();
if (!PyArg_ParseTuple(args, "i", &pid)) {
return NULL;
}
timer->pid = pid;
_StartTimer(timer);
return Py_BuildValue("iii", timer,timer->tid,timer->pid);
}
//Receives a pointer to a tmr_data struct object, deletes the timer contained inside it
static PyObject* ResetTimer(PyObject* self, PyObject* args)
{
tmr_data* timer;
long ptr_timer;
if (!PyArg_ParseTuple(args, "i", &ptr_timer)) {
return NULL;
}
timer = (tmr_data*)ptr_timer;
if(timer_delete(timer->tid) != 0)
{
perror("timer_delete");
exit(1);
}
return Py_BuildValue("iii", timer,timer->tid,timer->pid);
}
Now consider that the entire code of _StartTimer is correct: it's already been used in other parts of the project for pure C applications and, indeed, the timer does work here as well, at least the first time.
But still, this stuff is all over the place: originally I had ResetTimer calling _StartTimer, but whenever I'd call "timer = new tmr_data()" I would get segmentation fault, so I'm starting to think that the entire timer implementation might be somewhat tricky or prone to errors.

How to print the file path from an open syscall using ebpf python?

I use bpf from the python bcc module, and I want that my probe function will print the file path of the current file (kind of a custom simplified opensnoop).
How can I do that?
This is what I have so far:
b = BPF(text="""
#include <linux/ptrace.h>
#include<linux/sched.h>
BPF_HASH(last);
int trace_entry(struct pt_regs *ctx)
{
char fileName[200] = {0};
bpf_probe_read(fileName, sizeof(fileName), &PT_REGS_PARM1(ctx));
bpf_trace_printk("File Opened<%s>\\n", fileName);
return 0;
}
""")
print("Tracing for open... Ctrl-C to end")
b.attach_kprobe(event="do_sys_open", fn_name="trace_entry")
#b.attach_kprobe(event=b.get_syscall_fnname("open"), fn_name='funcky')
b.trace_print()
Easy:
Insert this in kernel code:
// Nicer way to call bpf_trace_printk()
#define bpf_custom_printk(fmt, ...) \
({ \
char ____fmt[] = fmt; \
bpf_trace_printk(____fmt, sizeof(____fmt), \
##__VA_ARGS__); \
})
struct pair {
uint32_t lip; // local IP
uint32_t rip; // remote IP
};
and in kernel code insert print out code. This function call works exactly like printf with all format and placeholder ...
bpf_custom_printk("This year is %d\n", 2020);
Print output:
sudo cat /sys/kernel/debug/tracing/trace_pipe

Python Netlink Multicast Communication in Kernels above 4

I was trying to reproduce the example from a previous SO post on a kernel above 4 (4.1):
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netlink.h>
#include <net/netlink.h>
#include <net/net_namespace.h>
/* Protocol family, consistent in both kernel prog and user prog. */
#define MYPROTO NETLINK_USERSOCK
/* Multicast group, consistent in both kernel prog and user prog. */
#define MYGRP 31
static struct sock *nl_sk = NULL;
static void send_to_user(void)
{
struct sk_buff *skb;
struct nlmsghdr *nlh;
char *msg = "Hello from kernel";
int msg_size = strlen(msg) + 1;
int res;
pr_info("Creating skb.\n");
skb = nlmsg_new(NLMSG_ALIGN(msg_size + 1), GFP_KERNEL);
if (!skb) {
pr_err("Allocation failure.\n");
return;
}
nlh = nlmsg_put(skb, 0, 1, NLMSG_DONE, msg_size + 1, 0);
strcpy(nlmsg_data(nlh), msg);
pr_info("Sending skb.\n");
res = nlmsg_multicast(nl_sk, skb, 0, MYGRP, GFP_KERNEL);
if (res < 0)
pr_info("nlmsg_multicast() error: %d\n", res);
else
pr_info("Success.\n");
}
static int __init hello_init(void)
{
pr_info("Inserting hello module.\n");
nl_sk = netlink_kernel_create(&init_net, MYPROTO, NULL);
if (!nl_sk) {
pr_err("Error creating socket.\n");
return -10;
}
send_to_user();
netlink_kernel_release(nl_sk);
return 0;
}
static void __exit hello_exit(void)
{
pr_info("Exiting hello module.\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
However, compilation works fine, but when I insert the module, it returns:
nlmsg_multicast() error: -3
I dont even know, where I can lookup the error codes to learn, what -3 means in this context (I searched here, but was unable to find anything useful, regarding the error code).
Just to be sure, I post the userland code (Python) also:
EDITED due to a comment: (but still not working)
#!/usr/bin/env python
import socket
import os
import time
sock = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, socket.NETLINK_USERSOCK)
# 270 is SOL_NETLINK and 1 is NETLINK_ADD_MEMBERSHIP
sock.setsockopt(270, 1, 31)
while 1:
try:
print sock.recvfrom(1024)
except socket.error, e:
print 'Exception'
You forgot to bind the socket. :-)
I'm not very fluent with Python, so use this only as a starting point (between the socket and the setsockopt):
sock.bind((0, 0))
That prints me a bunch of garbage, among which I can see
Hello from kernel
By the way: When nlmsg_multicast() throws ESRCH, it's usually (or maybe always) because there were no clients listening.
First open the client, then try to send the message from the kernel.
Otherwise you can always ignore that error code it that makes sense for your use case.

Can Python read from a Windows Powershell namedpipe?

I have the following named pipe created in Windows Powershell.
# .NET 3.5 is required to use the System.IO.Pipes namespace
[reflection.Assembly]::LoadWithPartialName("system.core") | Out-Null
$pipeName = "pipename"
$pipeDir = [System.IO.Pipes.PipeDirection]::InOut
$pipe = New-Object system.IO.Pipes.NamedPipeServerStream( $pipeName, $pipeDir )
Now, what i need is some Python code snippet to read from the above named pipe created. Can Python do that ?
Thanks in advance !
Courtesy :http://jonathonreinhart.blogspot.com/2012/12/named-pipes-between-c-and-python.html
Here's the C# Code
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
class PipeServer
{
static void Main()
{
var server = new NamedPipeServerStream("NPtest");
Console.WriteLine("Waiting for connection...");
server.WaitForConnection();
Console.WriteLine("Connected.");
var br = new BinaryReader(server);
var bw = new BinaryWriter(server);
while (true)
{
try
{
var len = (int)br.ReadUInt32(); // Read string length
var str = new string(br.ReadChars(len)); // Read string
Console.WriteLine("Read: \"{0}\"", str);
//str = new string(str.Reverse().ToArray()); // Aravind's edit: since Reverse() is not working, might require some import. Felt it as irrelevant
var buf = Encoding.ASCII.GetBytes(str); // Get ASCII byte array
bw.Write((uint)buf.Length); // Write string length
bw.Write(buf); // Write string
Console.WriteLine("Wrote: \"{0}\"", str);
}
catch (EndOfStreamException)
{
break; // When client disconnects
}
}
}
}
And here's the Python code:
import time
import struct
f = open(r'\\.\pipe\NPtest', 'r+b', 0)
i = 1
while True:
s = 'Message[{0}]'.format(i)
i += 1
f.write(struct.pack('I', len(s)) + s) # Write str length and str
f.seek(0) # EDIT: This is also necessary
print 'Wrote:', s
n = struct.unpack('I', f.read(4))[0] # Read str length
s = f.read(n) # Read str
f.seek(0) # Important!!!
print 'Read:', s
time.sleep(2)
Convert the C# code into a .ps1 file.

C to Python via SWIG: can't get void** parameters to hold their value

I have a C interface that looks like this (simplified):
extern bool Operation(void ** ppData);
extern float GetFieldValue(void* pData);
extern void Cleanup(p);
which is used as follows:
void * p = NULL;
float theAnswer = 0.0f;
if (Operation(&p))
{
theAnswer = GetFieldValue(p);
Cleanup(p);
}
You'll note that Operation() allocates the buffer p, that GetFieldValue queries p, and that Cleanup frees p. I don't have any control over the C interface -- that code is widely used elsewhere.
I'd like to call this code from Python via SWIG, but I was unable to find any good examples of how to pass a pointer to a pointer -- and retrieve its value.
I think the correct way to do this is by use of typemaps, so I defined an interface that would automatically dereference p for me on the C side:
%typemap(in) void** {
$1 = (void**)&($input);
}
However, I was unable to get the following python code to work:
import test
p = None
theAnswer = 0.0f
if test.Operation(p):
theAnswer = test.GetFieldValue(p)
test.Cleanup(p)
After calling test.Operation(), p always kept its initial value of None.
Any help with figuring out the correct way to do this in SWIG would be much appreciated. Otherwise, I'm likely to just write a C++ wrapper around the C code that stops Python from having to deal with the pointer. And then wrap that wrapper with SWIG. Somebody stop me!
Edit:
Thanks to Jorenko, I now have the following SWIG interface:
% module Test
%typemap (in,numinputs=0) void** (void *temp)
{
$1 = &temp;
}
%typemap (argout) void**
{
PyObject *obj = PyCObject_FromVoidPtr(*$1, Cleanup);
$result = PyTuple_Pack(2, $result, obj);
}
%{
extern bool Operation(void ** ppData);
extern float GetFieldValue(void *p);
extern void Cleanup(void *p);
%}
%inline
%{
float gfv(void *p){ return GetFieldValue(p);}
%}
%typemap (in) void*
{
if (PyCObject_Check($input))
{
$1 = PyCObject_AsVoidPtr($input);
}
}
The python code that uses this SWIG interface is as follows:
import test
success, p = test.Operation()
if success:
f = test.GetFieldValue(p) # This doesn't work
f = test.gvp(p) # This works!
test.Cleanup(p)
Oddly, in the python code, test.GetFieldValue(p) returns gibberish, but test.gfv(p) returns the correct value. I've inserting debugging code into the typemap for void*, and both have the same value of p! The call Any ideas about that?
Update: I've decided to use ctypes. MUCH easier.
I agree with theller, you should use ctypes instead. It's always easier than thinking about typemaps.
But, if you're dead set on using swig, what you need to do is make a typemap for void** that RETURNS the newly allocated void*:
%typemap (in,numinputs=0) void** (void *temp)
{
$1 = &temp;
}
%typemap (argout) void**
{
PyObject *obj = PyCObject_FromVoidPtr(*$1);
$result = PyTuple_Pack(2, $result, obj);
}
Then your python looks like:
import test
success, p = test.Operation()
theAnswer = 0.0f
if success:
theAnswer = test.GetFieldValue(p)
test.Cleanup(p)
Edit:
I'd expect swig to handle a simple by-value void* arg gracefully on its own, but just in case, here's swig code to wrap the void* for GetFieldValue() and Cleanup():
%typemap (in) void*
{
$1 = PyCObject_AsVoidPtr($input);
}
Would you be willing to use ctypes? Here is sample code that should work (although it is untested):
from ctypes import *
test = cdll("mydll")
test.Operation.restype = c_bool
test.Operation.argtypes = [POINTER(c_void_p)]
test.GetFieldValue.restype = c_float
test.GetFieldValue.argtypes = [c_void_p]
test.Cleanup.restype = None
test.Cleanup.argtypes = [c_void_p]
if __name__ == "__main__":
p = c_void_p()
if test.Operation(byref(p)):
theAnswer = test.GetFieldValue(p)
test.Cleanup(p)

Categories

Resources