how to read status registers of a printer in qnx - qnx

i am using an x86 processor.
the interface used to connect to the printer is a usb parallel port ieee1284.
i can send data to the printer no problem.
i have tested it with the following command.
cat file.txt > /dev/usbpar0
i have read on several forums that there is no base address for a usb parallel port.
what would be the easiest way of reading the status of the printer.
I need to know if it is out of paper or there is a paper jam. that is why i need to read the status registers.
I have included the source code i have tried to copy from [here][1]
#include <iostream>
#include <iomanip>
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include "stdlib.h"
#include "unistd.h"
#include "sys/io.h"
#include <hw/inout.h>
#include <stdint.h>
#include <sys/mman.h>
#include <stdio.h>
#include <fcntl.h> /* open() */
#include <sys/types.h> /* open() */
#include <sys/stat.h> /* open() */
#include <sys/ioctl.h>
#include "parport.h"
#include "ppdev.h"
#define DEVICE "/dev/usbpar0"
int write_data(int fd, unsigned char data);
int status_pins(int fd);
using namespace std;
int main(int argc, char **argv)
{
struct ppdev_frob_struct frob;
int fd;
int mode;
if((fd=open(DEVICE, O_RDWR)) < 0) {
fprintf(stderr, "can not open %s\n", DEVICE);
return 10;
}
ThreadCtl(_NTO_TCTL_IO, 0);
status_pins(fd);
close(fd);
return 0;
}
/* trivial example how to write data */
int write_data(int fd, unsigned char data)
{
return(ioctl(fd, PPWDATA, &data));
}
/* example how to read 8 bit from the data lines */
int read_data(int fd)
{
int mode, res;
unsigned char data;
mode = IEEE1284_MODE_ECP;
res=ioctl(fd, PPSETMODE, &mode); /* ready to read ? */
mode=255;
res=ioctl(fd, PPDATADIR, &mode); /* switch output driver off */
printf("ready to read data !\n");
fflush(stdout);
sleep(10);
res=ioctl(fd, PPRDATA, &data); /* now fetch the data! */
printf("data=%02x\n", data);
fflush(stdout);
sleep(10);
data=0;
res=ioctl(fd, PPDATADIR, data);
return 0;
}
/* example how to read the status lines. */
int status_pins(int fd)
{
int val;
ioctl(fd, PPRSTATUS, &val);
val^=PARPORT_STATUS_BUSY; /* /BUSY needs to get inverted */
printf("BUSY = %s\n",
((val & PARPORT_STATUS_BUSY)==PARPORT_STATUS_BUSY)?"HI":"LO");
printf("ERROR = %s\n",
((val & PARPORT_STATUS_ERROR)==PARPORT_STATUS_ERROR)?"HI":"LO");
printf("SELECT = %s\n",
((val & PARPORT_STATUS_SELECT)==PARPORT_STATUS_SELECT)?"HI":"LO");
printf("PAPEROUT = %s\n",
((val & PARPORT_STATUS_PAPEROUT)==PARPORT_STATUS_PAPEROUT)?"HI":"LO");
printf("ACK = %s\n",
((val & PARPORT_STATUS_ACK)==PARPORT_STATUS_ACK)?"HI":"LO");
return 0;
}
/* example how to use frob ... toggle STROBE on and off without messing
around the other lines */
int strobe_blink(int fd)
{
struct ppdev_frob_struct frob;
frob.mask = PARPORT_CONTROL_STROBE; /* change only this pin ! */
while(1) {
frob.val = PARPORT_CONTROL_STROBE; /* set STROBE ... */
ioctl(fd, PPFCONTROL, &frob);
usleep(500);
frob.val = 0; /* and clear again */
ioctl(fd, PPFCONTROL, &frob);
usleep(500);
}
}
"parport.h"
/* $Id: parport.h,v 1.1 1998/05/17 10:57:52 andrea Exp andrea $ */
/*
* Any part of this program may be used in documents licensed under
* the GNU Free Documentation License, Version 1.1 or any later version
* published by the Free Software Foundation.
*/
#ifndef _PARPORT_H_
#define _PARPORT_H_
/* Start off with user-visible constants */
/* Maximum of 16 ports per machine */
#define PARPORT_MAX 16
/* Magic numbers */
#define PARPORT_IRQ_NONE -1
#define PARPORT_DMA_NONE -1
#define PARPORT_IRQ_AUTO -2
#define PARPORT_DMA_AUTO -2
#define PARPORT_DMA_NOFIFO -3
#define PARPORT_DISABLE -2
#define PARPORT_IRQ_PROBEONLY -3
#define PARPORT_IOHI_AUTO -1
#define PARPORT_CONTROL_STROBE 0x1
#define PARPORT_CONTROL_AUTOFD 0x2
#define PARPORT_CONTROL_INIT 0x4
#define PARPORT_CONTROL_SELECT 0x8
#define PARPORT_STATUS_ERROR 0x8
#define PARPORT_STATUS_SELECT 0x10
#define PARPORT_STATUS_PAPEROUT 0x20
#define PARPORT_STATUS_ACK 0x40
#define PARPORT_STATUS_BUSY 0x80
/* Type classes for Plug-and-Play probe. */
typedef enum {
PARPORT_CLASS_LEGACY = 0, /* Non-IEEE1284 device */
PARPORT_CLASS_PRINTER,
PARPORT_CLASS_MODEM,
PARPORT_CLASS_NET,
PARPORT_CLASS_HDC, /* Hard disk controller */
PARPORT_CLASS_PCMCIA,
PARPORT_CLASS_MEDIA, /* Multimedia device */
PARPORT_CLASS_FDC, /* Floppy disk controller */
PARPORT_CLASS_PORTS,
PARPORT_CLASS_SCANNER,
PARPORT_CLASS_DIGCAM,
PARPORT_CLASS_OTHER, /* Anything else */
PARPORT_CLASS_UNSPEC, /* No CLS field in ID */
PARPORT_CLASS_SCSIADAPTER
} parport_device_class;
/* The "modes" entry in parport is a bit field representing the
capabilities of the hardware. */
#define PARPORT_MODE_PCSPP (1<<0) /* IBM PC registers available. */
#define PARPORT_MODE_TRISTATE (1<<1) /* Can tristate. */
#define PARPORT_MODE_EPP (1<<2) /* Hardware EPP. */
#define PARPORT_MODE_ECP (1<<3) /* Hardware ECP. */
#define PARPORT_MODE_COMPAT (1<<4) /* Hardware 'printer protocol'. */
#define PARPORT_MODE_DMA (1<<5) /* Hardware can DMA. */
#define PARPORT_MODE_SAFEININT (1<<6) /* SPP registers accessible in IRQ. */
/* IEEE1284 modes:
Nibble mode, byte mode, ECP, ECPRLE and EPP are their own
'extensibility request' values. Others are special.
'Real' ECP modes must have the IEEE1284_MODE_ECP bit set. */
#define IEEE1284_MODE_NIBBLE 0
#define IEEE1284_MODE_BYTE (1<<0)
#define IEEE1284_MODE_COMPAT (1<<8)
#define IEEE1284_MODE_BECP (1<<9) /* Bounded ECP mode */
#define IEEE1284_MODE_ECP (1<<4)
#define IEEE1284_MODE_ECPRLE (IEEE1284_MODE_ECP | (1<<5))
#define IEEE1284_MODE_ECPSWE (1<<10) /* Software-emulated */
#define IEEE1284_MODE_EPP (1<<6)
#define IEEE1284_MODE_EPPSL (1<<11) /* EPP 1.7 */
#define IEEE1284_MODE_EPPSWE (1<<12) /* Software-emulated */
#define IEEE1284_DEVICEID (1<<2) /* This is a flag */
#define IEEE1284_EXT_LINK (1<<14) /* This flag causes the
* extensibility link to
* be requested, using
* bits 0-6. */
/* For the benefit of parport_read/write, you can use these with
* parport_negotiate to use address operations. They have no effect
* other than to make parport_read/write use address transfers. */
#define IEEE1284_ADDR (1<<13) /* This is a flag */
#define IEEE1284_DATA 0 /* So is this */
/* Flags for block transfer operations. */
#define PARPORT_EPP_FAST (1<<0) /* Unreliable counts. */
#define PARPORT_W91284PIC (1<<1) /* have a Warp9 w91284pic in the device */
/* The rest is for the kernel only */
#endif /* _PARPORT_H_ */
"ppdev.h"
/*
* linux/include/linux/ppdev.h
*
* User-space parallel port device driver (header file).
*
* Copyright (C) 1998-9 Tim Waugh <tim#cyberelk.demon.co.uk>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Added PPGETTIME/PPSETTIME, Fred Barnes, 1999
* Added PPGETMODES/PPGETMODE/PPGETPHASE, Fred Barnes <frmb2#ukc.ac.uk>, 03/01/2001
*/
#define PP_IOCTL 'p'
/* Set mode for read/write (e.g. IEEE1284_MODE_EPP) */
#define PPSETMODE _IOW(PP_IOCTL, 0x80, int)
/* Read status */
#define PPRSTATUS _IOR(PP_IOCTL, 0x81, unsigned char)
#define PPWSTATUS OBSOLETE__IOW(PP_IOCTL, 0x82, unsigned char)
/* Read/write control */
#define PPRCONTROL _IOR(PP_IOCTL, 0x83, unsigned char)
#define PPWCONTROL _IOW(PP_IOCTL, 0x84, unsigned char)
struct ppdev_frob_struct {
unsigned char mask;
unsigned char val;
};
#define PPFCONTROL _IOW(PP_IOCTL, 0x8e, struct ppdev_frob_struct)
/* Read/write data */
#define PPRDATA _IOR(PP_IOCTL, 0x85, unsigned char)
#define PPWDATA _IOW(PP_IOCTL, 0x86, unsigned char)
/* Read/write econtrol (not used) */
#define PPRECONTROL OBSOLETE__IOR(PP_IOCTL, 0x87, unsigned char)
#define PPWECONTROL OBSOLETE__IOW(PP_IOCTL, 0x88, unsigned char)
/* Read/write FIFO (not used) */
#define PPRFIFO OBSOLETE__IOR(PP_IOCTL, 0x89, unsigned char)
#define PPWFIFO OBSOLETE__IOW(PP_IOCTL, 0x8a, unsigned char)
/* Claim the port to start using it */
#define PPCLAIM _IO(PP_IOCTL, 0x8b)
/* Release the port when you aren't using it */
#define PPRELEASE _IO(PP_IOCTL, 0x8c)
/* Yield the port (release it if another driver is waiting,
* then reclaim) */
#define PPYIELD _IO(PP_IOCTL, 0x8d)
/* Register device exclusively (must be before PPCLAIM). */
#define PPEXCL _IO(PP_IOCTL, 0x8f)
/* Data line direction: non-zero for input mode. */
#define PPDATADIR _IOW(PP_IOCTL, 0x90, int)
/* Negotiate a particular IEEE 1284 mode. */
#define PPNEGOT _IOW(PP_IOCTL, 0x91, int)
/* Set control lines when an interrupt occurs. */
#define PPWCTLONIRQ _IOW(PP_IOCTL, 0x92, unsigned char)
/* Clear (and return) interrupt count. */
#define PPCLRIRQ _IOR(PP_IOCTL, 0x93, int)
/* Set the IEEE 1284 phase that we're in (e.g. IEEE1284_PH_FWD_IDLE) */
#define PPSETPHASE _IOW(PP_IOCTL, 0x94, int)
/* Set and get port timeout (struct timeval's) */
#define PPGETTIME _IOR(PP_IOCTL, 0x95, struct timeval)
#define PPSETTIME _IOW(PP_IOCTL, 0x96, struct timeval)
/* Get available modes (what the hardware can do) */
#define PPGETMODES _IOR(PP_IOCTL, 0x97, unsigned int)
/* Get the current mode and phaze */
#define PPGETMODE _IOR(PP_IOCTL, 0x98, int)
#define PPGETPHASE _IOR(PP_IOCTL, 0x99, int)
/* get/set flags */
#define PPGETFLAGS _IOR(PP_IOCTL, 0x9a, int)
#define PPSETFLAGS _IOW(PP_IOCTL, 0x9b, int)
/* flags visible to the world */
#define PP_FASTWRITE (1<<2)
#define PP_FASTREAD (1<<3)
#define PP_W91284PIC (1<<4)
/* only masks user-visible flags */
#define PP_FLAGMASK (PP_FASTWRITE | PP_FASTREAD | PP_W91284PIC)

I managed to find a solution to my problem by using the devctl command. i could read the status of the printer.
#include <iostream>
#include <iomanip>
#include <devctl.h>
#include <sys/dcmd_chr.h>
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include "stdlib.h"
#include "unistd.h"
#include "sys/io.h"
#include <hw/inout.h>
#include <stdint.h>
#include <sys/mman.h>
#include <stdio.h>
#include <fcntl.h> /* open() */
#include <sys/types.h> /* open() */
#include <sys/stat.h> /* open() */
#include <sys/ioctl.h>
#include "parport.h"
#include "ppdev.h"
#define DEVICE "/dev/usbpar0"
int status_pins(int fd);
using namespace std;
int main(int argc, char **argv)
{
int fd;
if((fd=open(DEVICE, O_RDWR)) < 0) {
fprintf(stderr, "can not open %s\n", DEVICE);
return 10;
}
// ThreadCtl(_NTO_TCTL_IO, 0);
int data = 0, error;
if (error = devctl (fd, DCMD_CHR_LINESTATUS, &data,
sizeof(data), NULL))
{
fprintf(stderr, "Error setting RTS: %s\n",
strerror ( error ));
exit(EXIT_FAILURE);
}
if (data & _LINESTATUS_PAR_NOERROR)
{
printf("No Error Detected!\n");
}
else
{
printf("Error Detected\n");
}
if (data & _LINESTATUS_PAR_PAPEROUT)
{
printf("Paper Empty\n");
}
else
{
printf("Paper OK!\n");
}
close(fd);
return 0;
}

Related

Can't find erf, erff, etc. compiling under 10.2

I try to compile C++ Mathematical Expression Library (http://www.partow.net/programming/exprtk/index.html) by Arash Parto. Unfort. I do not succeed using 10.2. erf, erff, etc. are not found.
File try to compile:
#pragma hdrstop
#pragma argsused
#ifdef _WIN32
#include <tchar.h>
#else
typedef char _TCHAR;
#define _tmain main
#endif
#include <stdio.h>
#include <cmath>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <fstream>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
#include "exprtk.hpp"
#ifdef exprtk_test_float32_type
typedef float numeric_type;
#else
typedef double numeric_type;
#endif
some defs...
int _tmain(int argc, _TCHAR* argv[])
{
#define perform_test(Type,Number)
int result = 0;
perform_test(numeric_type,00)
#undef perform_test
return result;
}
=======================================
Error log:
Project "D:_Entwicklung.KEL\exprtk_new\Project2.cbproj" (Build target(s)):
Target CreateProjectDirectories:
Creating directory ".\Win32\Debug".
Compiling C++ files...
Target MakeObjs:
Target TCCompile:
C:\Program Files (x86)\JomiTech\TwineCompile\mtbcc32.exe -ide102 -priority0 -files="D:_Entwicklung.KEL\exprtk_new\twfiles.###"
JomiTech TwineCompile 4.5 - Copyright JomiTech 2016. All Rights Reserved.
Compiling 1 files...
Embarcadero C++ 7.30 for Win32 Copyright (c) 1993-2017 Embarcadero Technologies, Inc.
d:_Entwicklung.KEL\exprtk_new\File2.cpp
File2.cpp: (0) 0 of 0
File2.cpp: (0) 368546 of 368546
d:_Entwicklung.KEL\exprtk_new\exprtk.hpp(1200,49): C++ error E2268: Call to undefined function 'erff'
After Remy Lebau's advice I tried the following
#RemyLebeau: Thanks for your advice. However I feel so useless.....
I tried (of course no **):
**using namespace std;**
#if (defined(_MSC_VER) && (_MSC_VER >= 1900)) || !defined(_MSC_VER)
#define exprtk_define_erf(TT,impl) \
inline TT erf_impl(TT v) { return impl(v); } \
exprtk_define_erf( float,::erff)
exprtk_define_erf( double,::erf )
exprtk_define_erf(long double,::erfl)
#undef exprtk_define_erf
#endif
==> [bcc32c Error] exprtk.hpp(1199): no member named 'erff' in the global namespace
Then I tried:
#if (defined(_MSC_VER) && (_MSC_VER >= 1900)) || !defined(_MSC_VER)
#define exprtk_define_erf(TT,impl) \
inline TT erf_impl(TT v) { return impl(v); } \
exprtk_define_erf( float,**std**::erff)
exprtk_define_erf( double,**std**::erf )
exprtk_define_erf(long double,**std**::erfl)
#undef exprtk_define_erf
#endif
==> [bcc32c Error] exprtk.hpp(1198): no member named 'erff' in namespace 'std'
New file2.cpp
#pragma hdrstop
#pragma argsused
#ifdef _WIN32
#include <tchar.h>
#else
typedef char _TCHAR;
#define _tmain main
#endif
using namespace std;
#include "exprtk.hpp"
template <typename T>
void trig_function()
{
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::expression<T> expression_t;
typedef exprtk::parser<T> parser_t;
//
const std::string expression_string =
"clamp(-1.0,sin(2 * pi * x) + cos(x / 2 * pi),+1.0)";
T x;
symbol_table_t symbol_table;
symbol_table.add_variable("x",x);
symbol_table.add_constants();
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
parser.compile(expression_string,expression);
//
for (x = T(-5); x <= T(+5); x += T(0.001))
{
const T y = expression.value();
printf("%19.15f\t%19.15f\n", x, y);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
trig_function<double>();
int result = 0;
return result;
}
After modifiying in #include "exprtk.hpp":
#if (defined(_MSC_VER) && (_MSC_VER >= 1900)) || !defined(_MSC_VER)
#define exprtk_define_erf(TT,impl) \
inline TT erf_impl(TT v) { return impl(v); } \
// exprtk_define_erf( float,::erff)
exprtk_define_erf( double,::erf )
// exprtk_define_erf(long double,::erfl)
#undef exprtk_define_erf
#endif
I get now:
[ilink32 Error] Fatal: Exceeded memory limit for block Publics in module File2.cpp

How may I use PCAP or other library to parse layer 3 frame received from TUN?

This is how I receive layer 3 frame from TUN.
Written based on docs:
https://www.kernel.org/doc/Documentation/networking/tuntap.txt
http://backreference.org/2010/03/26/tuntap-interface-tutorial/
Unpacking from http://www.saminiir.com/lets-code-tcp-ip-stack-1-ethernet-arp/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <linux/if_tun.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/time.h>
#include <errno.h>
#include <stdarg.h>
/* buffer for reading from tun/tap interface, must be >= 1500 */
#define BUFSIZE 2000
int tun_alloc(char *dev)
{
struct ifreq ifr;
int fd, err;
if (!dev) {
return -1;
}
memset(&ifr, 0, sizeof(ifr));
/* Flags: IFF_TUN - TUN device (no Ethernet headers)
* IFF_TAP - TAP device
*
* IFF_NO_PI - Do not provide packet information
* IFF_MULTI_QUEUE - Create a queue of multiqueue device
*/
ifr.ifr_flags = IFF_TUN;
strcpy(ifr.ifr_name, dev);
if ((fd = open("/dev/net/tun", O_RDWR)) < 0)
return fd;
err = ioctl(fd, TUNSETIFF, (void *)&ifr);
if (err) {
close(fd);
goto err;
}
strcpy(dev, ifr.ifr_name);
return fd;
err:
close(fd);
return err;
}
int main() {
char *tun_name;
tun_name = malloc(IFNAMSIZ);
tun_name[0] = '\0';
int tun_fd = tun_alloc(tun_name);
if (tun_fd < 0) {
puts("Try as root");
exit(1);
}
if (ioctl(tun_fd, TUNSETPERSIST, 0) < 0) {
perror("disabling TUNSETPERSIST");
exit(1);
}
printf("Set interface '%s' nonpersistent\n", tun_name);
struct layer3_frame
{
uint16_t flags;
uint16_t proto;
uint8_t version;
unsigned char payload[];
} __attribute__((packed));
int nread;
char buffer[BUFSIZE];
while(1) {
nread = read(tun_fd, buffer, sizeof(buffer));
if(nread < 0) {
perror("Reading from interface");
close(tun_fd);
exit(1);
}
/* Do whatever with the data */
printf("Read %d bytes from device %s\n", nread, tun_name);
struct layer3_frame* l3f = (struct layer3_frame*)(buffer);
printf("FLAGS %d, PROTO %d, VER %d", l3f->flags, l3f->proto, l3f->version);
// E.g. FLAGS 0, PROTO 56710, VER 96
// Why PROTO is not 4 or 6, why VER is not 4 or 6?
// MAIN: HOW TO USE PCAP TO PARSE l3f FURTHER
// AND GET INFO UP TO SNI (server name indication), e.g.
}
return 0;
}
To play:
gcc index.c
sudo ./a.out
sudo ip link set tun0 up
PCAP usually is not used for parsing packets.
You may use however:
#include <netinet/ip.h>
#include <netinet/ip6.h>
//...
struct layer3_frame
{
uint16_t flags; // FLAGS from TUN
uint16_t proto; // PRPTO from TUN
unsigned char payload[]; // FRAME/PACKET
} __attribute__((packed));
const struct ip* ippacket = (struct ip*)(l3p->payload);
printf("Version is %d", ippacket->ip_v)
3. About strange values for PROTO like 56710 try printf("FFF: %x", ntohs(56710)) you will get 86dd which you may look up at https://en.wikipedia.org/wiki/EtherType

MobileDevice Framework AMDeviceCopyValue get ECID

(Hope this post don't get too messy)
Hello, I have a question about the AMDeviceCopyValue function in mobiledevice library, because I want to grab the ECID from a connected iDevice and print it, in the c console.
#include "MobileDevice.h"
void device_callback(struct am_device_notification_callback_info *info, void *arg) {
struct am_device *dev;
if (info->msg == ADNCI_MSG_CONNECTED) {
dev = info->dev;
CFRetain(dev);
AMDSetLogLevel(5);
AMDeviceConnect(dev);
assert(AMDeviceIsPaired(dev));
assert(!AMDeviceValidatePairing(dev));
assert(!AMDeviceStartSession(dev));
assert(AMDeviceIsPaired(dev));
assert(AMDeviceValidatePairing(dev) == 0);
CFStringRef Serial = AMDeviceCopyValue(dev, 0, CFSTR("SerialNumber"));
printf("Serial (%s)", CFStringGetCStringPtr(Serial, CFStringGetSystemEncoding()));
}
}
int main(int argc, char *argv[]) {
struct am_device_notification *notify;
AMDeviceNotificationSubscribe(&device_callback, 0, 0, NULL, &notify);
CFRunLoopRun();
}
This code will print out the serial number of the iDevice,but I want it to print out the ECID so I read at theiphonewiki that if I wanted to get the ECID I had to use the value "UniqueChipID" with the function (AMDeviceCopyValue) link
but that doesn't seem to work very well....
Cause if I edit the value from SerialNumber to UniqueChipID, and run the code it all crashes.... :(
so if you want to try to help me, first you have to create a header file(I called it MobileDevice.h) (you also have to add MobileDevice.framework (its a private apple framework found in /System/Library/PrivateFrameworks ) and add this code to the MobileDevice.h
/* ----------------------------------------------------------------------------
* MobileDevice.h - interface to MobileDevice.framework
* $LastChangedDate: 2007-07-09 18:59:29 -0700 (Mon, 09 Jul 2007) $
*
* Copied from http://iphonesvn.halifrag.com/svn/iPhone/
* With modifications from Allen Porter and Scott Turner
*
* ------------------------------------------------------------------------- */
#ifndef MOBILEDEVICE_H
#define MOBILEDEVICE_H
#ifdef __cplusplus
extern "C" {
#endif
#if defined(WIN32)
#include <CoreFoundation.h>
typedef unsigned int mach_error_t;
#elif defined(__APPLE__)
#include <CoreFoundation/CoreFoundation.h>
#include <mach/error.h>
#endif
/* Error codes */
#define MDERR_APPLE_MOBILE (err_system(0x3a))
#define MDERR_IPHONE (err_sub(0))
/* Apple Mobile (AM*) errors */
#define MDERR_OK ERR_SUCCESS
#define MDERR_SYSCALL (ERR_MOBILE_DEVICE | 0x01)
#define MDERR_OUT_OF_MEMORY (ERR_MOBILE_DEVICE | 0x03)
#define MDERR_QUERY_FAILED (ERR_MOBILE_DEVICE | 0x04)
#define MDERR_INVALID_ARGUMENT (ERR_MOBILE_DEVICE | 0x0b)
#define MDERR_DICT_NOT_LOADED (ERR_MOBILE_DEVICE | 0x25)
/* Apple File Connection (AFC*) errors */
#define MDERR_AFC_OUT_OF_MEMORY 0x03
/* USBMux errors */
#define MDERR_USBMUX_ARG_NULL 0x16
#define MDERR_USBMUX_FAILED 0xffffffff
/* Messages passed to device notification callbacks: passed as part of
* am_device_notification_callback_info. */
#define ADNCI_MSG_CONNECTED 1
#define ADNCI_MSG_DISCONNECTED 2
#define ADNCI_MSG_UNKNOWN 3
#define AMD_IPHONE_PRODUCT_ID 0x1290
#define AMD_IPHONE_SERIAL "3391002d9c804d105e2c8c7d94fc35b6f3d214a3"
/* Services, found in /System/Library/Lockdown/Services.plist */
#define AMSVC_AFC CFSTR("com.apple.afc")
#define AMSVC_BACKUP CFSTR("com.apple.mobilebackup")
#define AMSVC_CRASH_REPORT_COPY CFSTR("com.apple.crashreportcopy")
#define AMSVC_DEBUG_IMAGE_MOUNT CFSTR("com.apple.mobile.debug_image_mount")
#define AMSVC_NOTIFICATION_PROXY CFSTR("com.apple.mobile.notification_proxy")
#define AMSVC_PURPLE_TEST CFSTR("com.apple.purpletestr")
#define AMSVC_SOFTWARE_UPDATE CFSTR("com.apple.mobile.software_update")
#define AMSVC_SYNC CFSTR("com.apple.mobilesync")
#define AMSVC_SCREENSHOT CFSTR("com.apple.screenshotr")
#define AMSVC_SYSLOG_RELAY CFSTR("com.apple.syslog_relay")
#define AMSVC_SYSTEM_PROFILER CFSTR("com.apple.mobile.system_profiler")
typedef unsigned int afc_error_t;
typedef unsigned int usbmux_error_t;
typedef unsigned int service_conn_t;
struct am_recovery_device;
typedef struct am_device_notification_callback_info {
struct am_device *dev; /* 0 device */
unsigned int msg; /* 4 one of ADNCI_MSG_* */
} __attribute__ ((packed)) am_device_notification_callback_info;
/* The type of the device restore notification callback functions.
* TODO: change to correct type. */
typedef void (*am_restore_device_notification_callback)(struct
am_recovery_device *);
/* This is a CoreFoundation object of class AMRecoveryModeDevice. */
typedef struct am_recovery_device {
unsigned char unknown0[8]; /* 0 */
am_restore_device_notification_callback callback; /* 8 */
void *user_info; /* 12 */
unsigned char unknown1[12]; /* 16 */
unsigned int readwrite_pipe; /* 28 */
unsigned char read_pipe; /* 32 */
unsigned char write_ctrl_pipe; /* 33 */
unsigned char read_unknown_pipe; /* 34 */
unsigned char write_file_pipe; /* 35 */
unsigned char write_input_pipe; /* 36 */
} __attribute__ ((packed)) am_recovery_device;
/* A CoreFoundation object of class AMRestoreModeDevice. */
typedef struct am_restore_device {
unsigned char unknown[32];
int port;
} __attribute__ ((packed)) am_restore_device;
/* The type of the device notification callback function. */
typedef void(*am_device_notification_callback)(struct
am_device_notification_callback_info *, void* arg);
/* The type of the _AMDDeviceAttached function.
* TODO: change to correct type. */
typedef void *amd_device_attached_callback;
typedef struct am_device {
unsigned char unknown0[16]; /* 0 - zero */
unsigned int device_id; /* 16 */
unsigned int product_id; /* 20 - set to AMD_IPHONE_PRODUCT_ID */
char *serial; /* 24 - set to AMD_IPHONE_SERIAL */
unsigned int unknown1; /* 28 */
unsigned char unknown2[4]; /* 32 */
unsigned int lockdown_conn; /* 36 */
unsigned char unknown3[8]; /* 40 */
} __attribute__ ((packed)) am_device;
typedef struct am_device_notification {
unsigned int unknown0; /* 0 */
unsigned int unknown1; /* 4 */
unsigned int unknown2; /* 8 */
am_device_notification_callback callback; /* 12 */
unsigned int unknown3; /* 16 */
} __attribute__ ((packed)) am_device_notification;
typedef struct afc_connection {
unsigned int handle; /* 0 */
unsigned int unknown0; /* 4 */
unsigned char unknown1; /* 8 */
unsigned char padding[3]; /* 9 */
unsigned int unknown2; /* 12 */
unsigned int unknown3; /* 16 */
unsigned int unknown4; /* 20 */
unsigned int fs_block_size; /* 24 */
unsigned int sock_block_size; /* 28: always 0x3c */
unsigned int io_timeout; /* 32: from AFCConnectionOpen, usu. 0 */
void *afc_lock; /* 36 */
unsigned int context; /* 40 */
} __attribute__ ((packed)) afc_connection;
typedef struct afc_directory {
unsigned char unknown[0]; /* size unknown */
} __attribute__ ((packed)) afc_directory;
typedef struct afc_dictionary {
unsigned char unknown[0]; /* size unknown */
} __attribute__ ((packed)) afc_dictionary;
typedef unsigned long long afc_file_ref;
typedef struct usbmux_listener_1 { /* offset value in iTunes */
unsigned int unknown0; /* 0 1 */
unsigned char *unknown1; /* 4 ptr, maybe device? */
amd_device_attached_callback callback; /* 8 _AMDDeviceAttached */
unsigned int unknown3; /* 12 */
unsigned int unknown4; /* 16 */
unsigned int unknown5; /* 20 */
} __attribute__ ((packed)) usbmux_listener_1;
typedef struct usbmux_listener_2 {
unsigned char unknown0[4144];
} __attribute__ ((packed)) usbmux_listener_2;
typedef struct am_bootloader_control_packet {
unsigned char opcode; /* 0 */
unsigned char length; /* 1 */
unsigned char magic[2]; /* 2: 0x34, 0x12 */
unsigned char payload[0]; /* 4 */
} __attribute__ ((packed)) am_bootloader_control_packet;
/* ----------------------------------------------------------------------------
* Public routines
* ------------------------------------------------------------------------- */
void AMDSetLogLevel(int level);
/* Registers a notification with the current run loop. The callback gets
* copied into the notification struct, as well as being registered with the
* current run loop. dn_unknown3 gets copied into unknown3 in the same.
* (Maybe dn_unknown3 is a user info parameter that gets passed as an arg to
* the callback?) unused0 and unused1 are both 0 when iTunes calls this.
* In iTunes the callback is located from $3db78e-$3dbbaf.
*
* Returns:
* MDERR_OK if successful
* MDERR_SYSCALL if CFRunLoopAddSource() failed
* MDERR_OUT_OF_MEMORY if we ran out of memory
*/
mach_error_t AMDeviceNotificationSubscribe(am_device_notification_callback
callback, unsigned int unused0, unsigned int unused1, void* //unsigned int
dn_unknown3, struct am_device_notification **notification);
/* Connects to the iPhone. Pass in the am_device structure that the
* notification callback will give to you.
*
* Returns:
* MDERR_OK if successfully connected
* MDERR_SYSCALL if setsockopt() failed
* MDERR_QUERY_FAILED if the daemon query failed
* MDERR_INVALID_ARGUMENT if USBMuxConnectByPort returned 0xffffffff
*/
mach_error_t AMDeviceConnect(struct am_device *device);
/* Calls PairingRecordPath() on the given device, than tests whether the path
* which that function returns exists. During the initial connect, the path
* returned by that function is '/', and so this returns 1.
*
* Returns:
* 0 if the path did not exist
* 1 if it did
*/
int AMDeviceIsPaired(struct am_device *device);
/* iTunes calls this function immediately after testing whether the device is
* paired. It creates a pairing file and establishes a Lockdown connection.
*
* Returns:
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the supplied device is null
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
*/
mach_error_t AMDeviceValidatePairing(struct am_device *device);
/* Creates a Lockdown session and adjusts the device structure appropriately
* to indicate that the session has been started. iTunes calls this function
* after validating pairing.
*
* Returns:
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
*/
mach_error_t AMDeviceStartSession(struct am_device *device);
/* Starts a service and returns a handle that can be used in order to further
* access the service. You should stop the session and disconnect before using
* the service. iTunes calls this function after starting a session. It starts
* the service and the SSL connection. unknown may safely be
* NULL (it is when iTunes calls this), but if it is not, then it will be
* filled upon function exit. service_name should be one of the AMSVC_*
* constants. If the service is AFC (AMSVC_AFC), then the handle is the handle
* that will be used for further AFC* calls.
*
* Returns:
* MDERR_OK if successful
* MDERR_SYSCALL if the setsockopt() call failed
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
*/
mach_error_t AMDeviceStartService(struct am_device *device, CFStringRef
service_name, service_conn_t *handle, unsigned int *
unknown);
mach_error_t AMDeviceStartHouseArrestService(struct am_device *device, CFStringRef identifier, void *unknown, service_conn_t *handle, unsigned int *what);
/* Stops a session. You should do this before accessing services.
*
* Returns:
* MDERR_OK if successful
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
*/
mach_error_t AMDeviceStopSession(struct am_device *device);
/* Opens an Apple File Connection. You must start the appropriate service
* first with AMDeviceStartService(). In iTunes, io_timeout is 0.
*
* Returns:
* MDERR_OK if successful
* MDERR_AFC_OUT_OF_MEMORY if malloc() failed
*/
afc_error_t AFCConnectionOpen(service_conn_t handle, unsigned int io_timeout,
struct afc_connection **conn);
/* Pass in a pointer to an afc_device_info structure. It will be filled. */
afc_error_t AFCDeviceInfoOpen(afc_connection *conn, struct
afc_dictionary **info);
/* Turns debug mode on if the environment variable AFCDEBUG is set to a numeric
* value, or if the file '/AFCDEBUG' is present and contains a value. */
void AFCPlatformInit();
/* Opens a directory on the iPhone. Pass in a pointer in dir to be filled in.
* Note that this normally only accesses the iTunes sandbox/partition as the
* root, which is /var/root/Media. Pathnames are specified with '/' delimiters
* as in Unix style.
*
* Returns:
* MDERR_OK if successful
*/
afc_error_t AFCDirectoryOpen(afc_connection *conn, const char *path,
struct afc_directory **dir);
/* Acquires the next entry in a directory previously opened with
* AFCDirectoryOpen(). When dirent is filled with a NULL value, then the end
* of the directory has been reached. '.' and '..' will be returned as the
* first two entries in each directory except the root; you may want to skip
* over them.
*
* Returns:
* MDERR_OK if successful, even if no entries remain
*/
afc_error_t AFCDirectoryRead(afc_connection *conn/*unsigned int unused*/, struct afc_directory *dir,
char **dirent);
afc_error_t AFCDirectoryClose(afc_connection *conn, struct afc_directory *dir);
afc_error_t AFCDirectoryCreate(afc_connection *conn, const char *dirname);
afc_error_t AFCRemovePath(afc_connection *conn, const char *dirname);
afc_error_t AFCRenamePath(afc_connection *conn, const char *from, const char *to);
afc_error_t AFCLinkPath(afc_connection *conn, long long int linktype, const char *target, const char *linkname);
/* Returns the context field of the given AFC connection. */
unsigned int AFCConnectionGetContext(afc_connection *conn);
/* Returns the fs_block_size field of the given AFC connection. */
unsigned int AFCConnectionGetFSBlockSize(afc_connection *conn);
/* Returns the io_timeout field of the given AFC connection. In iTunes this is
* 0. */
unsigned int AFCConnectionGetIOTimeout(afc_connection *conn);
/* Returns the sock_block_size field of the given AFC connection. */
unsigned int AFCConnectionGetSocketBlockSize(afc_connection *conn);
/* Closes the given AFC connection. */
afc_error_t AFCConnectionClose(afc_connection *conn);
/* Registers for device notifications related to the restore process. unknown0
* is zero when iTunes calls this. In iTunes,
* the callbacks are located at:
* 1: $3ac68e-$3ac6b1, calls $3ac542(unknown1, arg, 0)
* 2: $3ac66a-$3ac68d, calls $3ac542(unknown1, 0, arg)
* 3: $3ac762-$3ac785, calls $3ac6b2(unknown1, arg, 0)
* 4: $3ac73e-$3ac761, calls $3ac6b2(unknown1, 0, arg)
*/
unsigned int AMRestoreRegisterForDeviceNotifications(
am_restore_device_notification_callback dfu_connect_callback,
am_restore_device_notification_callback recovery_connect_callback,
am_restore_device_notification_callback dfu_disconnect_callback,
am_restore_device_notification_callback recovery_disconnect_callback,
unsigned int unknown0,
void *user_info);
/* Causes the restore functions to spit out (unhelpful) progress messages to
* the file specified by the given path. iTunes always calls this right before
* restoring with a path of
* "$HOME/Library/Logs/iPhone Updater Logs/iPhoneUpdater X.log", where X is an
* unused number.
*/
unsigned int AMRestoreEnableFileLogging(char *path);
/* Initializes a new option dictionary to default values. Pass the constant
* kCFAllocatorDefault as the allocator. The option dictionary looks as
* follows:
* {
* NORImageType => 'production',
* AutoBootDelay => 0,
* KernelCacheType => 'Release',
* UpdateBaseband => true,
* DFUFileType => 'RELEASE',
* SystemImageType => 'User',
* CreateFilesystemPartitions => true,
* FlashNOR => true,
* RestoreBootArgs => 'rd=md0 nand-enable-reformat=1 -progress'
* BootImageType => 'User'
* }
*
* Returns:
* the option dictionary if successful
* NULL if out of memory
*/
CFMutableDictionaryRef AMRestoreCreateDefaultOptions(CFAllocatorRef allocator);
/* ----------------------------------------------------------------------------
* Less-documented public routines
* ------------------------------------------------------------------------- */
/* mode 2 = read, mode 3 = write */
afc_error_t AFCFileRefOpen(afc_connection *conn, const char *path,
unsigned long long mode, afc_file_ref *ref);
afc_error_t AFCFileRefSeek(afc_connection *conn, afc_file_ref ref,
unsigned long long offset1, unsigned long long offset2);
afc_error_t AFCFileRefRead(afc_connection *conn, afc_file_ref ref,
void *buf, unsigned int *len);
afc_error_t AFCFileRefSetFileSize(afc_connection *conn, afc_file_ref ref,
unsigned long long offset);
afc_error_t AFCFileRefWrite(afc_connection *conn, afc_file_ref ref,
const void *buf, unsigned int len);
afc_error_t AFCFileRefClose(afc_connection *conn, afc_file_ref ref);
afc_error_t AFCFileInfoOpen(afc_connection *conn, const char *path, struct
afc_dictionary **info);
afc_error_t AFCKeyValueRead(struct afc_dictionary *dict, char **key, char **
val);
afc_error_t AFCKeyValueClose(struct afc_dictionary *dict);
unsigned int AMRestorePerformRecoveryModeRestore(struct am_recovery_device *
rdev, CFDictionaryRef opts, void *callback, void *user_info);
unsigned int AMRestorePerformRestoreModeRestore(struct am_restore_device *
rdev, CFDictionaryRef opts, void *callback, void *user_info);
struct am_restore_device *AMRestoreModeDeviceCreate(unsigned int unknown0,
unsigned int connection_id, unsigned int unknown1);
unsigned int AMRestoreCreatePathsForBundle(CFStringRef restore_bundle_path,
CFStringRef kernel_cache_type, CFStringRef boot_image_type, unsigned int
unknown0, CFStringRef *firmware_dir_path, CFStringRef *
kernelcache_restore_path, unsigned int unknown1, CFStringRef *
ramdisk_path);
unsigned int AMDeviceGetConnectionID(struct am_device *device);
mach_error_t AMDeviceEnterRecovery(struct am_device *device);
mach_error_t AMDeviceDisconnect(struct am_device *device);
mach_error_t AMDeviceRetain(struct am_device *device);
mach_error_t AMDeviceRelease(struct am_device *device);
CFStringRef AMDeviceCopyValue(struct am_device *device, unsigned int, CFStringRef cfstring);
CFStringRef AMDeviceCopyDeviceIdentifier(struct am_device *device);
typedef void (*notify_callback)(CFStringRef notification, void *data);
mach_error_t AMDPostNotification(service_conn_t socket, CFStringRef notification, CFStringRef userinfo);
mach_error_t AMDObserveNotification(void *socket, CFStringRef notification);
mach_error_t AMDListenForNotifications(void *socket, notify_callback cb, void *data);
mach_error_t AMDShutdownNotificationProxy(void *socket);
/*edits by geohot*/
mach_error_t AMDeviceDeactivate(struct am_device *device);
mach_error_t AMDeviceActivate(struct am_device *device, CFMutableDictionaryRef);
/*end*/
void *AMDeviceSerialize(struct am_device *device);
void AMDAddLogFileDescriptor(int fd);
//kern_return_t AMDeviceSendMessage(service_conn_t socket, void *unused, CFPropertyListRef plist);
//kern_return_t AMDeviceReceiveMessage(service_conn_t socket, CFDictionaryRef options, CFPropertyListRef * result);
/* ----------------------------------------------------------------------------
* Semi-private routines
* ------------------------------------------------------------------------- */
/* Pass in a usbmux_listener_1 structure and a usbmux_listener_2 structure
* pointer, which will be filled with the resulting usbmux_listener_2.
*
* Returns:
* MDERR_OK if completed successfully
* MDERR_USBMUX_ARG_NULL if one of the arguments was NULL
* MDERR_USBMUX_FAILED if the listener was not created successfully
*/
usbmux_error_t USBMuxListenerCreate(struct usbmux_listener_1 *esi_fp8, struct
usbmux_listener_2 **eax_fp12);
/* ----------------------------------------------------------------------------
* Less-documented semi-private routines
* ------------------------------------------------------------------------- */
usbmux_error_t USBMuxListenerHandleData(void *);
/* ----------------------------------------------------------------------------
* Private routines - here be dragons
* ------------------------------------------------------------------------- */
/* AMRestorePerformRestoreModeRestore() calls this function with a dictionary
* in order to perform certain special restore operations
* (RESTORED_OPERATION_*). It is thought that this function might enable
* significant access to the phone. */
typedef unsigned int (*t_performOperation)(struct am_restore_device *rdev,
CFDictionaryRef op); // __attribute__ ((regparm(2)));
#ifdef __cplusplus
}
#endif
#endif
Would loved any help I can get!!!
And I hope this post isĀ“nt to messy?
The value associated with UniqueChipID is a CFNumber not a CFString.
4 : <CFString 0x7fa18bf62f90 [0x7fff7279ecf0]>{contents = "UniqueChipID"} = <CFNumber 0x18a19201535c55c5 [0x7fff7279ecf0]>{value = +0000000000000000, type = kCFNumberSInt64Type}
Incidentally, CFShow is your friend.
Example:
CFNumberRef ecid = AMDeviceCopyValue(dev, 0, CFSTR("UniqueChipID"));

obtaining scsi(including SAS and FC) hardisk model and serial number

I have recently been playing around with some hard drive stuff. Now what I want to do is print out the model and serial number of harddisk. Sata drives are very easy with ioctl. scsi on the other hand I have to send an inquiry command. I found a very helpful site which explains everything and even has a example program: http://tldp.org/HOWTO/archived/SCSI-Programming-HOWTO/SCSI-Programming-HOWTO-24.html
but I only get nothing or gibberish as a result if I print it out. I even had to fix the program as stdlib wasn't included and the function Inquiry returned a local variable. But I have no idea how to fix it...
#define DEVICE "/dev/sdb"
/* Example program to demonstrate the generic SCSI interface */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <scsi/sg.h>
#define SCSI_OFF sizeof(struct sg_header)
static unsigned char cmd[SCSI_OFF + 18]; /* SCSI command buffer */
int fd; /* SCSI device/file descriptor */
/* process a complete scsi cmd. Use the generic scsi interface. */
static int handle_scsi_cmd(unsigned cmd_len, /* command length */
unsigned in_size, /* input data size */
unsigned char *i_buff, /* input buffer */
unsigned out_size, /* output data size */
unsigned char *o_buff /* output buffer */
)
{
int status = 0;
struct sg_header *sg_hd;
/* safety checks */
if (!cmd_len) return -1; /* need a cmd_len != 0 */
if (!i_buff) return -1; /* need an input buffer != NULL */
#ifdef SG_BIG_BUFF
if (SCSI_OFF + cmd_len + in_size > SG_BIG_BUFF) return -1;
if (SCSI_OFF + out_size > SG_BIG_BUFF) return -1;
#else
if (SCSI_OFF + cmd_len + in_size > 4096) return -1;
if (SCSI_OFF + out_size > 4096) return -1;
#endif
if (!o_buff) out_size = 0;
/* generic scsi device header construction */
sg_hd = (struct sg_header *) i_buff;
sg_hd->reply_len = SCSI_OFF + out_size;
sg_hd->twelve_byte = cmd_len == 12;
sg_hd->result = 0;
#if 0
sg_hd->pack_len = SCSI_OFF + cmd_len + in_size; /* not necessary */
sg_hd->pack_id; /* not used */
sg_hd->other_flags; /* not used */
#endif
/* send command */
status = write( fd, i_buff, SCSI_OFF + cmd_len + in_size );
if ( status < 0 || status != SCSI_OFF + cmd_len + in_size ||
sg_hd->result ) {
/* some error happened */
fprintf( stderr, "write(generic) result = 0x%x cmd = 0x%x\n",
sg_hd->result, i_buff[SCSI_OFF] );
perror("");
return status;
}
if (!o_buff) o_buff = i_buff; /* buffer pointer check */
/* retrieve result */
status = read( fd, o_buff, SCSI_OFF + out_size);
if ( status < 0 || status != SCSI_OFF + out_size || sg_hd->result ) {
/* some error happened */
fprintf( stderr, "read(generic) result = 0x%x cmd = 0x%x\n",
sg_hd->result, o_buff[SCSI_OFF] );
fprintf( stderr, "read(generic) sense "
"%x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\n",
sg_hd->sense_buffer[0], sg_hd->sense_buffer[1],
sg_hd->sense_buffer[2], sg_hd->sense_buffer[3],
sg_hd->sense_buffer[4], sg_hd->sense_buffer[5],
sg_hd->sense_buffer[6], sg_hd->sense_buffer[7],
sg_hd->sense_buffer[8], sg_hd->sense_buffer[9],
sg_hd->sense_buffer[10], sg_hd->sense_buffer[11],
sg_hd->sense_buffer[12], sg_hd->sense_buffer[13],
sg_hd->sense_buffer[14], sg_hd->sense_buffer[15]);
if (status < 0)
perror("");
}
/* Look if we got what we expected to get */
if (status == SCSI_OFF + out_size) status = 0; /* got them all */
return status; /* 0 means no error */
}
#define INQUIRY_CMD 0x12
#define INQUIRY_CMDLEN 6
#define INQUIRY_REPLY_LEN 96
#define INQUIRY_VENDOR 8 /* Offset in reply data to vendor name */
/* request vendor brand and model */
static unsigned char *Inquiry ( void )
{
unsigned char Inqbuffer[ SCSI_OFF + INQUIRY_REPLY_LEN ];
unsigned char cmdblk [ INQUIRY_CMDLEN ] =
{ INQUIRY_CMD, /* command */
0, /* lun/reserved */
0, /* page code */
0, /* reserved */
INQUIRY_REPLY_LEN, /* allocation length */
0 };/* reserved/flag/link */
memcpy( cmd + SCSI_OFF, cmdblk, sizeof(cmdblk) );
/*
* +------------------+
* | struct sg_header | <- cmd
* +------------------+
* | copy of cmdblk | <- cmd + SCSI_OFF
* +------------------+
*/
if (handle_scsi_cmd(sizeof(cmdblk), 0, cmd,
sizeof(Inqbuffer) - SCSI_OFF, Inqbuffer )) {
fprintf( stderr, "Inquiry failed\n" );
exit(2);
}
return (Inqbuffer + SCSI_OFF);
}
void main( void )
{
fd = open(DEVICE, O_RDWR);
if (fd < 0) {
fprintf( stderr, "Need read/write permissions for "DEVICE".\n" );
exit(1);
}
/* print some fields of the Inquiry result */
printf( "||%s||", Inquiry() + INQUIRY_VENDOR );
}

SCTP Multistreaming: infinite loop

I have a simple client-server application on SCTP! The client connects to server opening 3 streams and the server sends a file per stream. The problem is that I don't know how to control the 3 streams, to know when sctp_rcvmsg() from a stream i 0 it would mean that the file transmission is ended for that stream...but it seems that sctp_recvmsg() never stops. here's my code.
CLIENT
#include <sys/types.h>
#include <sys/socket.h>
#include <signal.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdlib.h>
#include <time.h>
#define BUFFERSIZE 1024
int main(int argc, char** argv) {
int i, sockCliSCTP, flags, res;
/* Server netwrok informations */
struct sockaddr_in servAddr;
/* To get which stream it has received data from */
struct sctp_sndrcvinfo sndrcvinfo;
/* Init message to setup number of streams */
struct sctp_initmsg initmsg;
/* Catching events */
struct sctp_event_subscribe events;
/* Buffer to receive files */
char buffer[BUFFERSIZE];
/* Remove previous recently used files */
remove("first.txt");
remove("second.txt");
remove("third.txt");
char ipServ[32] = "127.0.0.1";
short int servPort = 29008;
/* BEGIN SCTP PART */
/* Creating client socket for SCTP protocol */
sockCliSCTP = socket( AF_INET, SOCK_STREAM, IPPROTO_SCTP );
/* Specify that a maximum of 3 streams will be available per socket */
memset( &initmsg, 0, sizeof(initmsg) );
initmsg.sinit_num_ostreams = 3; /* output streams */
initmsg.sinit_max_instreams = 3; /* input streams */
initmsg.sinit_max_attempts = 2;
setsockopt(sockCliSCTP, IPPROTO_SCTP, SCTP_INITMSG, &initmsg, sizeof(initmsg) );
/* Initializing server network data structs */
bzero( (void *)&servAddr, sizeof(servAddr) );
servAddr.sin_family = AF_INET;
inet_pton(AF_INET, ipServ, &servAddr.sin_addr);
servAddr.sin_port = htons(29008);
int sizeServ = sizeof(servAddr);
/* Connect to server */
res = connect(sockCliSCTP, (struct sockaddr *)&servAddr, sizeof(servAddr));
if (res < 0) {
printf("Connection to server refused!\n");
exit(1);
}
memset( (void *)&events, 0, sizeof(events) );
events.sctp_data_io_event = 1;
res = setsockopt(sockCliSCTP, SOL_SCTP, SCTP_EVENTS, (const void *)&events, sizeof(events));
if (res < 0) {
printf("setsockopt failed!\n");
exit(1);
}
/* The clients simply waits and receives for three files from the server.
* The size of the files is increased each time this client is launched. */
FILE *oneF, *twoF, *threeF;
oneF = fopen("first.txt", "a"); /* Stream 0 */
twoF = fopen("second.txt", "a"); /* Stream 1 */
threeF = fopen("third.txt", "a"); /* Stream 2 */
/* To measure time */
time_t timeStart;
time_t timeEnd;
time_t timeRes = 0;
time(&timeStart);
int count0 = 0, count1 = 0, count2 = 0;
int checkRead[3];
for(i = 0; i<3; i++) {
checkRead[i] = 1;
}
/* Receiving in parallel the files from 3 streams */
while(checkRead[0] || checkRead[1] || checkRead[2]) {
printf("%d %d %d\n", checkRead[0], checkRead[1], checkRead[2]);
res = sctp_recvmsg(sockCliSCTP, (void*)buffer, sizeof(buffer), (struct sockaddr*)&servAddr, (socklen_t *)&sizeServ, &sndrcvinfo, &flags);
if (res == 0) {
printf("%d stream is zero\n", sndrcvinfo.sinfo_stream);
checkRead[sndrcvinfo.sinfo_stream] = 0;
continue;
}
/* Check from which stream the data came in */
switch(sndrcvinfo.sinfo_stream) {
/* Write on file oneF --> first.txt */
case 0:
count0++;
printf("Message received from stream 0\n");
//printf("%s\n\n", buffer);
fprintf(oneF, "%s", buffer);
break;
/* Write on file twoF --> second.txt */
case 1:
count1++;
printf("Message received from stream 1\n");
//printf("%s\n\n", buffer);
fprintf(twoF, "%s", buffer);
break;
/* Write on file threeF --> third.txt */
case 2:
count2++;
printf("Message received from stream 2\n");
//printf("%s\n\n", buffer);
fprintf(threeF, "%s", buffer);
break;
}
memset(buffer, 0, sizeof(buffer));
sleep(1);
}
close(sockCliSCTP);
time(&timeEnd);
timeRes = timeEnd - timeStart;
printf("Time elapsed is: %d seconds\n", (int)timeRes);
printf("%d messages on stream 0,\n %d messages on stream 1,\n %d messages on stream 2\n", count0, count1, count2);
}
AND THE SERVER:
#include <sys/types.h>
#include <sys/socket.h>
#include <signal.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFFERSIZE 1024
int main(int argc, char** argv) {
int sockCli, sockServ, one, two, three, i, res;
struct sockaddr_in client, server;
/* data struct to declarate streams */
struct sctp_initmsg initmsg;
/* buffer to read from file */
char buffer[BUFFERSIZE];
/* socket server listening */
sockServ = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP);
bzero( (void *)&client, sizeof(client));
bzero( (void *)&server, sizeof(server));
/* Preparing sever data struct and bind() */
bzero( (void *)&server, sizeof(server) );
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl( INADDR_ANY );
server.sin_port = htons(29008);
bind(sockServ, (struct sockaddr *)&server, sizeof(server));
/* Maximum of 3 streams will be available per socket */
memset( &initmsg, 0, sizeof(initmsg) );
initmsg.sinit_num_ostreams = 3;
initmsg.sinit_max_instreams = 3;
initmsg.sinit_max_attempts = 2;
res = setsockopt(sockServ, IPPROTO_SCTP, SCTP_INITMSG, &initmsg, sizeof(initmsg));
if (res < 0) {
printf("setsockopt() failed!\n");
exit(1);
}
/* Preparing the three files to be sent */
one = open("files/first.txt", O_RDONLY);
if (one < 0) {
printf("Error on opening first file!\n");
exit(1);
}
two = open("files/second.txt", O_RDONLY);
if (two < 0) {
printf("Error on opening second file!\n");
exit(1);
}
three = open("files/third.txt", O_RDONLY);
if (three < 0) {
printf("Error on opening third files!\n");
exit(1);
}
int checkFiles[3];
for(i=0; i<3; i++) {
checkFiles[i] = 1;
}
res = listen(sockServ, 5);
if (res < 0) {
printf("listen() failed!\n");
exit(1);
}
while(1) {
ssize_t readRes;
int len = sizeof(client);
sockCli = accept(sockServ, (struct sockaddr*)&client, &len);
if (sockCli < 0) {
printf("Error on accept()!\n");
exit(1);
}
printf("Associated to client!\n");
while(1) {
memset(buffer, 0, sizeof(buffer));
if ((readRes = read(one, (void*)buffer, sizeof(buffer))) > 0) {
sctp_sendmsg(sockCli, (void*)buffer, (size_t)strlen(buffer), NULL, 0, 0, 0, 0 /* stream number */, 0, 0);
}
memset(buffer, 0, sizeof(buffer));
if ((readRes = read(two, (void*)buffer, sizeof(buffer))) > 0) {
sctp_sendmsg(sockCli, (void*)buffer, (size_t)strlen(buffer), NULL, 0, 0, 0, 1 /* stream number */, 0, 0);
}
memset(buffer, 0, sizeof(buffer));
if ((readRes = read(three, (void*)buffer, sizeof(buffer))) > 0) {
sctp_sendmsg(sockCli, (void*)buffer, (size_t)strlen(buffer), NULL, 0, 0, 0, 2 /* stream number */, 0, 0);
}
else {break;}
}
close(sockCli);
close(one);
close(two);
close(three);
}
}
Where am I making a mistake? :(
sctp_recvmsg doesn't receive a message from a single stream. It simply returns ANY message received and then the application can figure out which stream the message came from.
After all the data has been received by your client when this code executes:
res = sctp_recvmsg(sockCliSCTP, (void*)buffer, sizeof(buffer), (struct sockaddr*)&servAddr, (socklen_t *)&sizeServ, &sndrcvinfo, &flags);
if (res == 0) {
printf("%d stream is zero\n", sndrcvinfo.sinfo_stream);
checkRead[sndrcvinfo.sinfo_stream] = 0;
continue;
}
res becomes 0 since no message is received and the sndrcvinfo structure does not get changed. So sndrcvinfo.sinfo_stream will remain equal to whatever stream the last message came from and you will get stuck in a loop since you won't change the checkRead[] values.
There's some other errors that will make the server/client behave strangely.
For example you can't run the client twice in a row without a a segmentation fault since the server closes the file descriptors and won't send any data the second time. Because of this you will segfault when you do:
checkRead[sndrcvinfo.sinfo_stream] = 0;
since sndrcvinfo will be a null pointer.

Resources