Parsing /proc psinfo and argv returns: Value too large for defined data type error - solaris

I have a fairly simple code below for processing /proc/* files in solaris to obtain process information and arguments. For the most part it works (meaning it does present arguments correctly on some processes), but on some process arguments (particularly where they are long), it fails and produces the error Value too large for defined data type
Does anyone have any idea perhaps why it fails?
It is the pread() line for the arguments array that fails at line 108.
It is actually some java processes with many arguments where it fails if that helps.
What's interesting too is that:
examining the binary /proc/<pid>/psinfo file, it is very small--the size is clearly not sufficient to contain the kind of long arguments that I am looking at with some processes. Doing hex dump of the contents of the psinfo file confirms that they are not there.
the value of pr_argv when there are long arguments is zero.
On further digging, it looks like the arguments are in /proc/(pid)/object/tmpfs.394.2.71404854. I wonder why.
Code:
#include <dirent.h>
#include <ctype.h>
#include <assert.h>
#include <malloc.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/processor.h>
#include <sys/sysinfo.h>
#include <sys/param.h>
#include <kstat.h>
#include <procfs.h>
#define PROC_ERRNO ((errno == ENOENT) ? ESRCH : errno)
#define my_pread(fd, ptr, type, offset) \
(pread(fd, ptr, sizeof(type), offset) == sizeof(type))
static int proc_psinfo_get(psinfo_t *psinfo, pid_t pid)
{
int fd, retval = 0;
char buffer[BUFSIZ];
sprintf(buffer, "/proc/%d/psinfo", pid);
if ((fd = open(buffer, O_RDONLY)) < 0) {
return ESRCH;
}
if (!my_pread(fd, psinfo, psinfo_t, 0)) {
retval = errno;
}
close(fd);
return retval;
}
int main(int argc, char **argv)
{
DIR *dirp = opendir("/proc");
struct dirent *ent;
char *models[] = {
"unknown", "32bit", "64bit"
};
while ((ent = readdir(dirp))) {
pid_t pid;
psinfo_t psinfo;
int retval;
char buffer[BUFSIZ];
char *argvb[56];
char **argvp = argvb;
int n, fd;
size_t nread = 0;
unsigned int argv_size;
if (!isdigit(*ent->d_name)) {
continue;
}
psinfo.pr_dmodel = 0;
pid = strtoul(ent->d_name, NULL, 10);
retval = proc_psinfo_get(&psinfo, pid);
printf("---------------------------------\n");
printf("pid=%d, status=%s, model=%s\n",
pid, retval ? strerror(retval) : "OK",
models[psinfo.pr_dmodel]);
printf("Parent Pid: %ld\n", psinfo.pr_ppid);
printf("UID: %ld\n", psinfo.pr_uid);
printf("size: %ld\n", psinfo.pr_size);
printf("rss: %ld\n", psinfo.pr_rssize);
printf("pcpu: %d\n", psinfo.pr_pctcpu);
printf("pctmem: %d\n", psinfo.pr_pctmem);
printf("zoneid: %d\n", psinfo.pr_zoneid);
printf("pr_sname: %c\n", psinfo.pr_lwp.pr_sname);
printf("Up Start: (%ld, %ld)\n", psinfo.pr_start.tv_sec, psinfo.pr_start.tv_nsec);
printf("Command: %s\n", psinfo.pr_fname);
// print argc
argv_size = sizeof(*argvp) * psinfo.pr_argc;
sprintf(buffer, "/proc/%d/as", pid);
printf("argc=%d, argv_size=%d\n",
psinfo.pr_argc, argv_size);
if ((fd = open(buffer, O_RDONLY)) < 0) {
printf("open(%s) == %s\n",
buffer, strerror(PROC_ERRNO));
if (argvp != argvb) {
free(argvp);
}
continue;
}
if (argv_size > sizeof(argvb)) {
argvp = malloc(argv_size);
}
if ((long int)(nread = pread(fd, argvp, argv_size, (off_t)psinfo.pr_argv)) <= 0) {
close(fd);
printf("error in reading argvp\n");
printf(" pread(%d, 0x%lx, %d, 0x%lx) == %d (%s)\n",
fd, (unsigned long)argvp, argv_size,
(unsigned long)psinfo.pr_argv,
nread, strerror(errno));
continue;
}
// parse the args here
for (n = 0; n < psinfo.pr_argc; n++) {
int alen;
char *arg;
if ((long int)(nread = pread(fd, buffer, sizeof(buffer), (off_t)argvp[n])) <= 0) {
close(fd);
printf("buffer %d argvp as ld %ld argvp as lu %lu ", sizeof(buffer), argvp[n] , argvp[n] );
printf(" %-2d) pread(%d, 0x%lx, %d, 0x%lx) == %d (%s)\n",
n, fd, (unsigned long)&buffer[0], sizeof(buffer),
(unsigned long)argvp[n],
nread, strerror(errno));
break;
}
printf(" %-2d) nread=%-4d, ", n, nread);
fflush(stdout);
alen = strlen(buffer)+1;
printf(" alen=%-4d ", alen);
fflush(stdout);
arg = malloc(alen);
memcpy(arg, buffer, alen);
printf(" {%s}\n", arg);
fflush(stdout);
}
if (argvp != argvb) {
free(argvp);
}
close(fd);
}
closedir(dirp);
return 0;
}

You're trying to read from a starting position past the end of the file.
From the pread man page:
ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
...
EOVERFLOW
The file is a regular file, nbyte is greater than 0, the starting
position is before the end-of-file, and the starting position is
greater than or equal to the offset maximum established in the open
file description associated with fildes.

Related

Segmentation fault on scanf?

I don't understand why the scanf call causes segmentation error. Tried making a separate file with only int number and scanf and it worked no problem. Really confused here need help. I use pointer in the scanf parameter so I'm suspecting the error might come from the interaction between scanf and shared memory somehow?
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <semaphore.h>
int main() {
const char *name = "message";
const char *names = "sem";
const int SIZE = 4096;
const int size = 1;
int number;
int shm_fd1;
int shm_fd2;
char *ptr; // Pointer to shared memory
sem_t *sem;
/* create the shared memory segment */
shm_fd1 = shm_open(name, O_CREAT | O_RDWR, 0666);
shm_fd2 = shm_open(names, O_CREAT | O_RDWR, 0666);
/* configure the size of the shared memory segment */
ftruncate(shm_fd1, SIZE);
ftruncate(shm_fd2, size);
/* initialize semaphore */
if (sem_init(sem, 1, 1) < 0) { // 1 = multiprocess
fprintf(stderr, "ERROR: could not initialize semaphore.\n");
exit(0);
}
/* now map the shared memory segment in the address space of the process */
ptr = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd1, 0);
sem = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd2, 0);
if (ptr == MAP_FAILED) {
printf("Map failed\n");
return -1;
}
if (sem == MAP_FAILED) {
printf("Map failed\n");
return -1;
}
strcpy(ptr, "Hello from the server\n");
/* store and read from the shared memory region */
printf("Message: %s\n", ptr);
printf("0. Quit\n 1. Change message\n 2. Check message\n");
printf("Type an integer: ");
scanf("%d", &number); //confirmed this causes the error
if I remove the line above the program runs no problem. the part alone also works fine apart from this file.
if (number == 1) {
sem_wait(sem);
printf("Enter your message: ");
scanf("%s", ptr);
sem_post(sem);
}
else if (number == 2) {
printf("Message: %s\n", ptr);
}
else {
/*break;*/
}
/* remove the shared memory segment */
if (shm_unlink(name) == -1) {
printf("Error removing %s\n",name);
exit(-1);
}
return 0;
}

The client sents message to the server and shows error couldn't sent, whats the problem in the program

The client program:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define LEN 256
int main(int argc, char *argv[]) {
struct addrinfo hints;
struct addrinfo *result, *rp;
int sock, s, n, r;
char message[256] , receive[1024];
int msglen, recvlen;
if (argc < 3)
{
fprintf(stderr, "Usage: %s host port msg...\n", argv[0]);
exit(EXIT_FAILURE);
}
/* Obtain address(es) matching host/port */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* streaming socket */
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
s = getaddrinfo(argv[1], argv[2], &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully connect(2).
If socket(2) (or connect(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == -1)
continue;
if (connect(sock, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */
close(sock);
}
if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "Could not connect\n");
exit(EXIT_FAILURE);
}
/* Send remaining command-line arguments as separate
datagrams, and read responses from server */
while(1)
{
bzero(message, LEN );
fgets(message, LEN, stdin);
printf("The server sent: %s\n",message);
n = send(sock, message, strlen(message), 0);
{
fprintf(stderr, "Could not send\n");
exit(EXIT_FAILURE);
}
bzero(message, 255);
n = recv(sock, message, LEN, 0);
if (n < 0)
{
fprintf(stderr, "Could not receive\n");
exit(EXIT_FAILURE);
}
printf("The client received: %s\n", message);
int i = strncmp("Exit", receive, 4);
if(i == 0)
break;
}
return 0;
}
The server program:
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#define LEN 256
int main(int argc, char *argv[]) {
struct addrinfo hints;
struct addrinfo *result, *rp;
struct sockaddr_in storage;
int sock, s,l,a,n;
char receive[LEN], response[1024];
int recvlen = strlen(receive);
pid_t childpid;
if (argc != 2)
{
fprintf(stderr, "Usage: %s port\n", argv[0]);
exit(EXIT_FAILURE);
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
hints.ai_flags = 0; /* For wildcard IP address */
hints.ai_protocol = 0; /* Any protocol */
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
s = getaddrinfo(NULL, argv[1], &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully bind(2).
If socket(2) (or bind(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == -1)
continue;
if (bind(sock, rp->ai_addr, rp->ai_addrlen) == 0)
break; /* Success */
close(sock);
}
if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "Could not bind\n");
exit(EXIT_FAILURE);
}
l = listen(sock, 5);
if(l != 0)
{
fprintf(stderr, "error in listening\n");
exit(EXIT_FAILURE);
}
socklen_t str_storage = sizeof(storage);
a = accept(sock, (struct sockaddr*)&storage, &str_storage);
if(a < 0)
{
fprintf(stderr, "the acceptance is not done\n");
exit(EXIT_FAILURE);
}
while(1)
{
bzero(receive, LEN);
n = recv(a, receive, LEN , 0);
if(n < 0)
{
fprintf(stderr, "error in reading\n");
exit(EXIT_FAILURE);
}
printf("The client message: %s\n ", receive);
bzero(receive, LEN);
fgets(receive, LEN, stdin);
n = send(a, receive, recvlen, 0);
if(n < 0)
{
fprintf(stderr, "error in replying\n");
exit(EXIT_FAILURE);
}
int i = strncmp("Exit", receive, 4);
if(i == 0)
break;
printf("The server message: %s\n", receive);
}
close(a);
return 0;
}
linux output both sides:
$ ./client localhost 5690
deeeksha hey
The server sent: deeeksha hey
Could not send
server output:
$ ./server 5690
The client message: deeeksha hey
n = send(sock, message, strlen(message), 0);
{
fprintf(stderr, "Could not send\n");
exit(EXIT_FAILURE);
}
Your client is executing this block no matter if the send was successful or not. It looks like you've forgot to check for if (n<0) but instead just had a block without any condition. Likely a case of copy & paste from somewhere else in your code by forgetting to copy the first line.

map reserver memory at boot to user space using remap_pfn_range

I am trying to map reserved memory (30M with offset of 2G) at boot time (boot kernel parameters mem=2G memmap=30M$2G) to user space using the remap_pfn_range, bellow is my driver code:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <asm/uaccess.h>
// #include <asm/error.h>
#define MAP_MAJOR 150
#define RAW_DATA_SIZE 0x1E00000 // 30 Mo
#define RAW_DATA_OFFSET 0x80000000 //2G
int results;
static void *rawdataStart = NULL;
static int map_mmap(struct file *filp, struct vm_area_struct *vma);
struct file_operations map_fops = {
.open = nonseekable_open,
.mmap = map_mmap
};
static int map_mmap(struct file *filp, struct vm_area_struct *vma) {
if (rawdataStart == NULL) {
printk(KERN_ERR "Memory not mapped!\n");
return -EAGAIN;
}
if ((vma->vm_end - vma->vm_start) != RAW_DATA_SIZE) {
printk(KERN_ERR "Error: sizes don't match (buffer size = %d, requested size = %lu)\n", RAW_DATA_SIZE, vma->vm_end - vma->vm_start);
return -EAGAIN;
}
results = remap_pfn_range(vma, vma->vm_start, RAW_DATA_OFFSET >> PAGE_SHIFT, RAW_DATA_SIZE, PAGE_SHARED);
if (results != 0) {
printk(KERN_ERR "Error in calling remap_pfn_range: returned %d\n", results);
return -EAGAIN;
}
return 0;
}
static int __init map_init(void)
{
printk("init map module\n");
if (register_chrdev(MAP_MAJOR,"mapReserved", &map_fops) <0 )
{
printk("unable to get major for map module\n");
return -EBUSY;
}
rawdataStart = ioremap(RAW_DATA_OFFSET, RAW_DATA_SIZE);
if (rawdataStart == NULL) {
printk(KERN_ERR "Unable to remap memory\n");
return 1;
}
printk(KERN_INFO "ioremap returned %p\n", rawdataStart);
return 0;
}
void __exit map_cleanup(void)
{
printk("exit map module\n");
unregister_chrdev(MAP_MAJOR,"mapReserved");
if (rawdataStart != NULL) {
printk(KERN_INFO "Unmapping memory at %p\n", rawdataStart);
iounmap(rawdataStart);
} else {
printk(KERN_WARNING "No memory to unmap!\n");
}
return;
}
MODULE_LICENSE("GPL");
module_init( map_init);
module_exit( map_cleanup);
and my user space app is below
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#define RAW_DATA_SIZE 0x1E00000
int main(void)
{
void * data;
int fd = open("/dev/mapReserved", O_RDWR);
if (fd == -1) {
perror("open error...\n");
return -1;
}
data = mmap(NULL, RAW_DATA_SIZE, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, 4096);
close(fd);
return 0;
}
when i insert the module it's return
[ 873.621763] init map module
[ 873.623175] ioremap returned fb580000
but when i am executing the user space app it's return error
open error...
I've resolved this problem following those references :
1- Reserve memory in Linux driver module and share it using driver mmap
2- mmap of several GB of reserved memory using
in my case i am reserving 30M from the offset 2G and bellow is the code
module:
// #include <linux/config.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/debugfs.h>
#include <linux/kernel.h> /* printk() */
#include <linux/slab.h> /* kmalloc() */
#include <linux/fs.h> /* everything... */
#include <linux/errno.h> /* error codes */
#include <linux/types.h> /* size_t */
#include <linux/mm.h>
#include <linux/kdev_t.h>
#include <asm/page.h>
#include <linux/cdev.h>
#include <linux/device.h>
#ifndef VM_RESERVED
# define VM_RESERVED (VM_DONTEXPAND | VM_DONTDUMP)
#endif
#define RAW_DATA_SIZE 31457280
#define RAW_DATA_OFFSET 0x80000000UL
void *rawdataStart;
struct dentry *file;
/*
* Open the device; in fact, there's nothing to do here.
*/
int simple_open (struct inode *inode, struct file *filp)
{
return 0;
}
/*
* Closing is just as simpler.
*/
static int simple_release(struct inode *inode, struct file *filp)
{
return 0;
}
static int simple_remap_mmap(struct file *filp, struct vm_area_struct *vma)
{
int ret;
unsigned long mapoffset;
mapoffset = RAW_DATA_OFFSET + (vma->vm_pgoff << PAGE_SHIFT);
ret = remap_pfn_range(vma, vma->vm_start, mapoffset >> PAGE_SHIFT,
vma->vm_end - vma->vm_start, PAGE_SHARED);
if ( ret != 0 ) {
printk("Error remap_pfn_range. \n");
return -EAGAIN;
}
return 0;
}
/* Device uses remap_pfn_range */
static struct file_operations simple_remap_ops = {
.owner = THIS_MODULE,
.open = simple_open,
.release = simple_release,
.mmap = simple_remap_mmap,
};
/*
* Module housekeeping.
*/
static int simple_init(void)
{
file = debugfs_create_file("mmap_example", 0644, NULL, NULL, &simple_remap_ops);
rawdataStart = ioremap(RAW_DATA_OFFSET, RAW_DATA_SIZE);
if (rawdataStart!=NULL){
printk("rawdataStart at:%p \n", rawdataStart);
memset(rawdataStart, 'c', 20971520);
memset(rawdataStart+20971520, '$', 100);
}else{
printk("rawdataStart is NULL \n");
return -1;
}
return 0;
}
static void simple_cleanup(void)
{
debugfs_remove(file);
if (rawdataStart != NULL) {
printk(KERN_INFO "Unmapping memory at %p\n", rawdataStart);
iounmap(rawdataStart);
} else {
printk(KERN_WARNING "No memory to unmap!\n");
}
}
module_init(simple_init);
module_exit(simple_cleanup);
MODULE_AUTHOR("Jonathan Corbet");
MODULE_LICENSE("Dual BSD/GPL");
and the user space App:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>
#define RAW_DATA_SIZE 31457280
int main(int argc, char **argv) {
int configfd;
char * address = NULL;
unsigned long chkSum;
FILE *fp = fopen("results.log", "w+");
configfd = open("/sys/kernel/debug/mmap_example", O_RDWR);
if (configfd < 0) {
perror("Open call failed");
return -1;
}
address = (unsigned char*) mmap(NULL, RAW_DATA_SIZE, PROT_WRITE,
MAP_PRIVATE, configfd, 0);
if (address == MAP_FAILED) {
perror("mmap operation failed");
return -1;
}
fputs(address, fp);
fclose(fp);
close(configfd);
return 0;
}

How can I know the service name?

This code from Stevens et al., Advanced Programming in the Unix Environment, Figure 16.17 is a server program to provide system uptime:
#include "apue.h"
#include <netdb.h>
#include <errno.h>
#include <syslog.h>
#include <sys/socket.h>
#define BUFLEN 128
#define QLEN 10
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 256
#endif
extern int initserver(int, const struct sockaddr *, socklen_t, int);
void
serve(int socked);
int
main(int argc, char *argv[])
{
struct addrinfo *ailist, *aip;
struct addrinfo hint;
int sockfd, err, n;
char *host;
if (argc != 1)
err_quit("usage: ruptimed");
if ((n = sysconf(_SC_HOST_NAME_MAX)) < 0)
n = HOST_NAME_MAX; /* best guess */
if ((host = malloc(n)) == NULL)
err_sys("malloc error");
if (gethostname(host, n) < 0)
err_sys("gethostname error");
daemonize("ruptimed");
memset(&hint, 0, sizeof(hint));
hint.ai_flags = AI_CANONNAME;
hint.ai_socktype = SOCK_STREAM;
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
if ((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0) {
syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s",
gai_strerror(err));
exit(1);
}
for (aip = ailist; aip != NULL; aip = aip->ai_next) {
if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr,
aip->ai_addrlen, QLEN)) >= 0) {
serve(sockfd);
exit(0);
}
}
exit(1);
}
What confused me is the function call getaddrinfo, it just tells me the service name is ruptime, and I have no idea where this name comes from. Did the service-name get named after the name of this program? How can I determine the service name? Can I designate the service name by myself?
I didn't duplicate the code of initserver and serve, because I think it doesn't concern the question.
The service name is simply a key to look up in /etc/services; i.e. it's a symbolic reference to a port number.

How to return to menu in Socket Client-Server

I've writen this code but it doesn't work correctly.
This is menu interface:
*************ENCODE_DECODE_BASE64**************
******* 1. Encode ********
******* 2. Decode ********
******* 3. Exit ********
***********************************************
When i choose 1, "Encode". The function runs but the process exits.
I want when I choose 1, the function to run and then after that, the menu to display again.
Can you help me?
Here is Clientcode:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#define MAX 1024
// read filename
char *inputString(int size){
int test=0;
char *s=(char*)malloc(size);
do{
if(test!=0){
printf("File not found !!!!!!");
}
fgets(s,size,stdin);
test++;
}while(strlen(s)<=1);
return strtok(s,"\n");
}
int main(int argc, char *argv[]){
int sockfd;
struct sockaddr serverAddr; //server address
char buff[1024];
struct sockaddr_in inAddr;
long int sentBytes,revedBytes;
sockfd=socket(AF_INET,SOCK_STREAM,0); // create socket
if (sockfd == -1)
{
printf("ERROR opening socket\n");
return 1;
}
printf("Socket done\n");
inAddr.sin_family=AF_INET; //default
inAddr.sin_port=htons(5500); // service port
inet_aton("127.0.0.1",&inAddr.sin_addr);
//connectting
if(connect(sockfd,(struct sockaddr *)&inAddr,sizeof(struct sockaddr))<0){
printf("Connect failed.\n");
return 1;
}
printf("Connection accepted\n");
char *FileName; // file input
char *Result; // file return
int choice;
do{
printf("\n*************ENCODE_DECODE_BASE64**************");
printf("\n******* 1. Encode ********");
printf("\n******* 2. Decode ********");
printf("\n******* 3. Exit ********");
printf("\n***********************************************\n");
printf("Choice: ");
choice = getchar();
while(getchar() !='\n');
switch(choice)
{
case '1':
//demo encode////////////////////////////////////////
send(sockfd,"encode",5,0); // send to server when choose 1
printf("File Encode : ");
FileName = inputString(20);
FILE *fpt = fopen(FileName,"r");
if(fpt==NULL){
printf("File not found");
return -1;
}
printf("File Result: ");
Result = inputString(20);
FILE *ft = fopen(Result,"w");
while(!feof(fpt)){
if (fgets(buff,MAX,fpt) != NULL ){
sentBytes=send(sockfd,buff,1024,0);
revedBytes=recv(sockfd,buff,1024,0);
fprintf(ft,"%s\n",buff);
}
}
printf("Encode done!thanks you !\n");
//close(sockfd);
fclose(fpt);fclose(ft);
return 0;
break;
//decode ///////////////////////////////////////////////
case '2':
send(sockfd,"decode",6,0);
printf("File Decode : ");
FileName = inputString(20);
FILE *fpt1 = fopen(FileName,"r");
if(fpt1==NULL){
printf("File not found");
return -1;
}
printf("File Result : ");
Result = inputString(20);
FILE *ft1 = fopen(Result,"w");
while(!feof(fpt1)){
if (fgets(buff,MAX,fpt1) != NULL ){
sentBytes=send(sockfd,buff,1024,0);
revedBytes=recv(sockfd,buff,1024,0);
fprintf(ft1,"%s",buff);
}
}
printf("Decode done ! thanks you !\n");
//close(sockfd);
fclose(fpt1);fclose(ft1);
return 0;
break;
///////////////////////////////////////////////////////
case '3':
printf("Thanks!\n");
break;
default: printf("wrong number, please try again!\n"); break;
//end choice///////////////////////////////////////
}
}while(choice!='3');
//end menu
//close(sockfd);
//return 0;
}
and here is ServerCode:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/* decodeblock - decode 4 '6-bit' characters into 3 8-bit binary bytes */
void decodeblock(unsigned char in[], char *clrstr) {
unsigned char out[4];
out[0] = in[0] << 2 | in[1] >> 4;
out[1] = in[1] << 4 | in[2] >> 2;
out[2] = in[2] << 6 | in[3] >> 0;
out[3] = '\0';
strncat(clrstr, out, sizeof(out));
}
void b64_decode(char *b64src, char *clrdst) {
int c, phase, i;
unsigned char in[4];
char *p;
clrdst[0] = '\0';
phase = 0; i=0;
while(b64src[i]) {
c = (int) b64src[i];
if(c == '=') {
decodeblock(in, clrdst);
break;
}
p = strchr(b64, c);
if(p) {
in[phase] = p - b64;
phase = (phase + 1) % 4;
if(phase == 0) {
decodeblock(in, clrdst);
in[0]=in[1]=in[2]=in[3]=0;
}
}
i++;
}
}
/* encodeblock - encode 3 8-bit binary bytes as 4 '6-bit' characters */
void encodeblock( unsigned char in[], char b64str[], int len ) {
unsigned char out[5];
out[0] = b64[ in[0] >> 2 ];
out[1] = b64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
out[2] = (unsigned char) (len > 1 ? b64[ ((in[1] & 0x0f) << 2) |
((in[2] & 0xc0) >> 6) ] : '=');
out[3] = (unsigned char) (len > 2 ? b64[ in[2] & 0x3f ] : '=');
out[4] = '\0';
strncat(b64str, out, sizeof(out));
}
/* encode - base64 encode a stream, adding padding if needed */
void b64_encode(char *clrstr, char *b64dst) {
unsigned char in[3];
int i, len = 0;
int j = 0;
b64dst[0] = '\0';
while(clrstr[j]) {
len = 0;
for(i=0; i<3; i++) {
in[i] = (unsigned char) clrstr[j];
if(clrstr[j]) {
len++; j++;
}
else in[i] = 0;
}
if( len ) {
encodeblock( in, b64dst, len );
}
}
}
void sig_chld(int signo) //child
{
pid_t pid;
int stat;
while((pid = waitpid(-1, &stat, WNOHANG))>0)
printf("child %d terminated\n", pid);
return;
}
int main()
{
int listen_sock, conn_sock;
int server_len, client_len,choice;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
char myb64[1024] = ""; //encode
char mydst[1024] = ""; //decode
int sentBytes,revedBytes,bytes_readi;
char buff[1024]; //buffer to send data
listen_sock = socket(AF_INET, SOCK_STREAM, 0); //create socket
if (listen_sock == -1)
{
printf("ERROR opening socket\n");
return 0;
}
printf("Socket done\n");
//Thiet lap dia chi server
server_address.sin_family = AF_INET; //default
inet_aton("127.0.0.1",&server_address.sin_addr); //ip server
server_address.sin_port = htons(5500); // port server
server_len = sizeof(server_address);
if(bind(listen_sock, (struct sockaddr *)&server_address,server_len)<0)
{
printf("ERROR on binding\n");
return 0;
}
printf("Bind done\n");
int check = listen(listen_sock,10);
if (check == -1)
{
printf("Error connect");
return 0;
}
printf("Waiting connect..\n");
while(1) {
client_len = sizeof(client_address);
conn_sock = accept(listen_sock,(struct sockaddr *)&client_address, &client_len);
if(conn_sock==-1){
printf("Error connect\n");
return 1;
}else{
printf("Accept new connection\n");
}
if(fork() == 0){
close(listen_sock);
do{
revedBytes = recv(conn_sock,buff,1024,0);
buff[revedBytes]='\0';
if(strcmp(buff,"mahoa")==0) choice=1;
else if(strcmp(buff,"giaima")==0) choice=2; else choice = 3;
switch(choice)
{
case 1:
while((revedBytes = recv(conn_sock,buff,1024,0)) > 0){
buff[revedBytes]='\0';
//printf("string send by client encode : %s\n",buff);
b64_encode(buff, myb64); //ma hoa
sentBytes=send(conn_sock,myb64,1024,0); //gui lai string da ma hoa cho client
}
close(conn_sock);//Dong ket noi cua client
exit(0);
break;
case 2:
while((revedBytes = recv(conn_sock,buff,1024,0)) > 0){
buff[revedBytes]='\0';
//printf("string send by client decode: %s\n",buff);
b64_decode(buff,mydst); // giaima
sentBytes=send(conn_sock,mydst,1024,0);
}
close(conn_sock);
exit(0);
break;
case 3:break;
}
}while(choice!=3);
break;
}
signal(SIGCHLD,sig_chld);
close(conn_sock);
}
return 1;
}