VISVESVARAYA TECHNOLOGICAL UNIVERSITY “Jnana Sangama”, Belagavi – 590 018

A PROJECT REPORT ON “SECURE USING LIBEVENTS WITH ADVANCED ACCESS CONTROL LISTS” Submitted in partial fulfillment for the award of the degree of BACHELOR OF ENGINEERING IN COMPUTER SCIENCE AND ENGINEERING BY ASHIK E (1NH12CS016) K BALAJI (1NH12CS048) NAGARAJ (1NH12CS068)

Under the guidance of Mrs.TINU N.S (Assistant Professor, Dept. of CSE, NHCE)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING NEW HORIZON COLLEGE OF ENGINEERING (ISO-9001:2000 certified, Accredited by NAAC ‘A’ , Permanently affiliated to VTU) Outer Ring Road, Panathur Post, Near Marathalli, Bangalore – 560103 NEW HORIZON COLLEGE OF ENGINEERING (ISO-9001:2000 certified, Accredited by NAAC ‘A’ Permanently affiliated to VTU) Outer Ring Road, Panathur Post, Near Marathalli, Bangalore-560 103 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

Certified that the project work entitled “SECURE FILE TRANSFER PROTOCOL USING LIBEVENTS WITH ADVANCED ACCESS CONTROL LISTS” carried out by ASHIK E (1NH12CS016), K BALAJI (1NH12CS048), and NAGARAJ C (1NH12CS068) bonafide students of NEW HORIZON COLLEGE OF ENGINEERING in partial fulfillment for the award of Bachelor Of Engineering in Computer Science and Engineering of the Visvesvaraya Technological University, Belgaum during the year 2015- 2016. It is certified that all corrections/suggestions indicated for Internal Assessment have been incorporated in the report deposited in the department library. The project report has been approved as it satisfies the academic requirements in respect of Project work prescribed for the said Degree.

Name & Signature of Guide Name Signature of HOD Signature of Principal (Mrs. Tinu N.S) (Dr. Prashanth C.S.R.) (Dr. Manjunatha)

Name of Examiner External Viva Signature with date 1. 2.

ACKNOWLEDGEMENT

The satisfaction and euphoria that accompany the successful completion of any task would be, but impossible without the mention of the people who made it possible, whose constant guidance and encouragement crowned our efforts with success.

We thank the management, Dr. Mohan Manghnani, Chairman of NEW HORIZON EDUCTIONAL INSTITUTIONS for providing necessary infrastructure and creating good environment.

We also record here the constant encouragement and facilities extended to us by Dr. Manjunatha, Principal, NHCE and Dr. Prashanth.C.S.R, Dean Academics, Head of the Department of Computer Science and Engineering. We extend our sincere gratitude to them.

We express our gratitude to Ms. Tinu N.S, our project guide for constantly monitoring the development of the project and setting up precise deadlines. Their valuable suggestions were the motivating factors in completing the work.

We express our gratitude to Ms. Clara Kanmani, our project co-ordinator for constantly monitoring the development of the project and setting up precise deadlines. Their valuable suggestions were the motivating factors in completing the work.

We would also like to express our gratitude to NHCE and to all our external guides at NHCE for their continuous guidance and motivation.

Finally a note of thanks to the teaching and non-teaching staff of Computer Science and Engineering Department for their cooperation extended to us and our friends, who helped us directly or indirectly in the course of the project work.

ASHIK E (1NH12CS016) K BALAJI (1NH12CS048) NAGARAJ C (1NH12CS068)

I

II

ABSTRACT

It is a network protocol that provides file access or file transfer over any reliable data . There are few methods which can be used like fork(), pthread(parallel thread), lib events.File Transfer Protocol (FTP) is a standard network protocol used to copy a file from one host to another over a TCP/IP-based network, such as the Internet. FTP is built on a client-server architecture and utilizes separate control and data connections between the client and server. FTP users may authenticate themselves using a clear-text sign-in protocol but can connect anonymously if the server is configured to allow it. Normally, we use thousands of threads to accept request by many clients. Here, we use libevents which helps in creating very few threads that can accept thousands of requests given by the clients without slowing down the system. The main objective is to provide file access or file transfer with only 2 or 3 threads without slowing down the system.The uploaded files can be put time restrictions using timer event.The files transfer can be authenticated.The server can be programmed based on events and activities.

I

CONTENTS

1. INTRODUCTION 1.1. SECURED FILE TRANSFER PROTOCOL 1 1.2. PROBLEM STATEMENT 3 1.3. PROJECT PURPOSE 3

2. LITERATURE SURVEY 2.1. EXISTING SYSTEM 4 2.2. PROPOSED SYSTEM 4 2.3. SOFTWARE DESCRIPTION 5 2.4. RELATIONS TO OTHER LANGUAGES 7

3. REQUIREMENT ANALYSIS 3.1. FUNCTIONAL REQUIREMENTS 8 3.2. NON FUNCTIONAL REQUIREMENTS 8 3.3. HARDWARE REQUIREMENTS 10 3.4. SOFTWARE REQUIREMENTS 10

4. DESIGN 4.1. LIBEVENT 11 4.2. DESIGN GOALS 11 4.3. LIBRARIES 12 4.4. BEANCHMARK 13 4.5. HEADERS 14 4.6. RECOGNIZED FLAGS 14 4.7. BUFFEREVENTS:CONCEPTS AND BASICS 16 4.8. CALLBACK AND WATERMARKS 17

II

5. IMPLEMENTATION 5.1. CONNECTION OF SFTP 20 5.2. EVENT MANAGEMENT 20 5.3. TIMER EVENT 21 5.4. PWD 21 5.5. CD 22 5.6. LS 22 5.7. TIME TO LIVE 23

6. TESTING 6.1 UNIT TESTING 25 6.2 INTEGRATION TESTING 25 6.3 VALIDATION TESTING 26

7. SNAPSHOT 27-31

8. CONCLUSION AND FUTURE ENHANCEMENT 8.1 CONCLUSION 32 8.2 FUTURE ENHANCEMENT 32

9. BIBLIOGRAPHY 35

III

IV

Secure File Transfer Protocol using LibEvent

CHAPTER 1

INTRODUCTION

1.1 SECURE FILE TRANSFER PROTOCOL

File Transfer Protocol (FTP) is a standard network protocol used to copy a file from one host to another over a TCP/IP-based network, such as the Internet. FTP is built on a client-server architecture and utilizes separate control and data connections between the client and server. FTP users may authenticate themselves using a clear-text sign-in protocol but can connect anonymously if the server is configured to allow it. FTP, or "File Transfer Protocol" is a popular method of transferring files between two remote systems. SFTP, which stands for SSH File Transfer Protocol, or Secure File Transfer Protocol, is a separate protocol packaged with SSH that works in a similar way over a secure connection. The advantage is the ability to leverage a secure connection to transfer files and traverse the on both the local and remote system. In almost all cases, SFTP is preferable to FTP because of its underlying security features and ability to piggy-back on an SSH connection. FTP is an insecure protocol that should only be used in limited cases or on networks you trust. Although SFTP is integrated into many graphical tools, this guide will demonstrate how to use it through its interactive command line interface. The first FTP client applications were interactive command-line tools, implementing standard commands and syntax. Graphical user interface clients have since been developed for many of the popular desktop operating systems in use today. FTP runs over the Transmission Control Protocol (TCP). Usually FTP servers listen on the well-known port number 21 (IANA-reserved) for incoming connections from clients. A connection to this port from the FTP client forms the control stream on which commands are passed to the FTP server and responses are collected. FTP uses out-of- band control; it opens dedicated data connections on other port numbers. The parameters for the data streams depend on the specifically requested transport mode. Data connections usually use port number 20. Dept of CSE, NHCE 1

Secure File Transfer Protocol using LibEvent

In active mode, the FTP client opens a dynamic port, sends the FTP server the dynamic port number on which it is listening over the control stream and waits for a connection from the FTP server. When the FTP server initiates the data connection to the FTP client it binds the source port to port 20 on the FTP server. In order to use active mode, the client sends a PORT command, with the IP and port as argument. The format for the IP and port is "h1,h2,h3,h4,p1,p2". Each field is a decimal representation of 8 bits of the host IP, followed by the chosen data port. For example, a client with an IP of 192.168.0.1, listening on port 49154 for the data connection will send the command "PORT 192,168,0,1,192,2". The port fields should be interpreted as p1?256 + p2 = port, or, in this example, 192?256 + 2 = 49154. In passive mode, the FTP server opens a dynamic port, sends the FTP client the server's IP address to connect to and the port on which it is listening (a 16-bit value broken into a high and low , as explained above) over the control stream and waits for a connection from the FTP client. In this case, the FTP client binds the source port of the connection to a dynamic port. To use passive mode, the client sends the PASV command to which the server would reply with something similar to "227 Entering Passive Mode (127,0,0,1,192,52)". The syntax of the IP address and port are the same as for the argument to the PORT command. In extended passive mode, the FTP server operates exactly the same as passive mode, however it only transmits the port number (not broken into high and low ) and the client is to assume that it connects to the same IP address that was originally connected to. Extended passive mode was added by RFC 2428 in September 1998. While data is being transferred via the data stream, the control stream sits idle. This can cause problems with large data transfers through firewalls which time out sessions after lengthy periods of idleness. While the file may well be successfully transferred, the control session can be disconnected by the firewall, causing an error to be generated.

Dept of CSE, NHCE 2

Secure File Transfer Protocol using LibEvent

1.2 PROBLEM DEFINITION File Transfer Protocol (FTP) is a standard Internet protocol for transmitting files between computers on the Internet over TCP/IP connections. FTP is a client-server protocol that relies on two communications channels between client and server: a command channel for controlling the conversation and a data channel for transmitting file content. Clients initiate conversations with servers by requesting to download a file. Using FTP, a client can upload, download, delete, rename, move and copy files on a server. A user typically needs to log on to the FTP server, although some servers make some or all of their content available without login, also known as anonymous FTP. FTP sessions work in passive or active modes. In active mode, after a client initiates a session via a command channel request, the server initiates a data connection back to the client and begins transferring data. In passive mode, the server instead uses the command channel to send the client the information it needs to open a data channel. Because passive mode has the client initiating all connections, it works well across firewalls and Network Address Translation (NAT) gateways.

1.3 PROJECT PURPOSE

It is a network protocol that provides file access or file transfer over any reliable data stream. There are few methods which can be used like fork(), pthread(parallel threading), libevents. Normally, we use thousands of threads to accecpt request by many clients. Here, we use libevents which helps in creating very few threads that accept thousands of request given by the client without slowing down the system.

Dept of CSE, NHCE 3

Secure File Transfer Protocol using LibEvent

CHAPTER 2 LITERATURE SURVEY 2.1 EXISTING SYSTEM With the current FTP the functionality is limited you cannot maintain different aspects of files like integrity and restrictions. In a system where files are transfer is time critical, there is no way to achieve this. For example if a file is transferred by a clientIf and this file has to be transferred or downloaded in fixed time say 3 hrs (after it is uploaded) then the present ftp cannot achieve this. Also if the file transfer has to be authenticated the options in the current ftp are limited. The other problem is that if the connections are to be detected or reported, there is no way to do this efficiently. For example, if you want to monitor an incoming connection and take certain action as soon as the connection happens it is not possible.

Disadvantages:

. There is no way to put time bar on the file uploaded. . User can transfer any files and can download any files without any time restrictions. . The server cannot monitor and delegate different aspects based on different events or activities.

2.2 PROPOSED SYSTEM To overcome the time critical problem, the ftp can be implemented using the libevent library in (Unix) c programming. The libevent API provides a mechanism to execute a callback function when a specific event occurs on a file descriptor or after a timeout has been reached. So when a file is transferred to the server then the then the libevent library can be programmed so that the timer is set on that file. If the file is downloaded before the timer expires then the file will be allowed to be downloaded. If the timer expires(or times out) then the file will be denied to be downloaded further by any other client. For this the libevent library of unix programming is configured to monitor for incoming files and set the timer on each files. The timer can be configured to any value(seconds) as required.

Dept of CSE, NHCE 4

Secure File Transfer Protocol using LibEvent

The libevent can also be configured to monitor each incoming connections and fire appropriate call back functions on each connections. Advantages:

. The uploaded files can be put time restrictions using timer event. . The files transfer can be authenticated. . The server can be programmed based on events and activities.

2.3 SOFTWARE DESCRIPTION C C is a general purpose imperative computer programming language, supporting structured programming lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, and therefore it has found lasting use in applications that had formerly been coded in assembly language, including operating systems, as well as various application software for computers ranging from supercomputers to embedded systems. C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs, and used to re-implement the Unix . It has since become one of the most widely used programming languages of all time, with C compilers from various vendors available for the majority of existing computer architectures and operating systems. C has been standardized by theAmerican National Standards Institute (ANSI) since 1989 (see ANSI C) and subsequently by the International Organization for Standardization (ISO). The C language also exhibits the following characteristics:

 There is a small, fixed number of keywords, including a full set of flow of control primitives: for, if/else, while, switch, and do/while. There is one namespace, and user-defined names are not distinguished from keywords by any kind of sigil.  There are a large number of arithmetical and logical operators, such as +, +=, ++, &, ~, etc.  More than one assignment may be performed in a single statement.

Dept of CSE, NHCE 5

Secure File Transfer Protocol using LibEvent

 Function return values can be ignored when not needed.  Typing is static, but weakly enforced: all data has a type, but implicit conversions can be performed; for instance, characters can be used as integers.  Declaration syntax mimics usage context. C has no "define" keyword; instead, a statement beginning with the name of a type is taken as a declaration. There is no "function" keyword; instead, a function is indicated by the parentheses of an argument list.  User-defined (typedef) and compound types are possible.

 Heterogeneous aggregate data types (struct) allow related data elements to be accessed and assigned as a unit.  Array indexing is a secondary notation, defined in terms of pointer arithmetic. Unlike structs, arrays are not first-class objects; they cannot be assigned or compared using single built-in operators. There is no "array" keyword, in use or definition; instead, square brackets indicate arrays syntactically, for example month.  Enumerated types are possible with the enum keyword. They are not tagged, and are freely interconvertible with integers.  Strings are not a separate data type, but are conventionally implemented as null- terminated arrays of characters.

 Low-level access to computer memory is possible by converting machine addresses to typed pointers.  Procedures (subroutines not returning values) are a special case of function, with an untyped return type void.  Functions may not be defined within the lexical scope of other functions.  Function and data pointers permit ad hoc run-time polymorphism.  A preprocessor performs macro definition, source code file inclusion, and conditional compilation.  There is a basic form of modularity: files can be compiled separately and linked together, with control over which functions and data objects are visible to other files viastatic and extern attributes.

Dept of CSE, NHCE 6

Secure File Transfer Protocol using LibEvent

 Complex functionality such as I/O, string manipulation, and mathematical functions are consistently delegated to library routines.

C does not include some features found in newer, more modern high-level languages, including object orientation and garbage collection.

2.4 Relations to other languages Many later languages have borrowed directly or indirectly from C, including C++, D, Go, Rust, Java, JavaScript, Limbo, LPC, C#, Objective- C, Perl, PHP, Python, Verilog(hardware description language),[4] and Unix's C shell. These languages have drawn many of their control structures and other basic features from C. Most of them (with Python being the most dramatic exception) are also very syntactically similar to C in general, and they tend to combine the recognizable expression and statement syntax of C with underlying type systems, data models, and semantics that can be radically different.

Dept of CSE, NHCE 7

Secure File Transfer Protocol using LibEvent

CHAPTER 3 REQUIREMENT ANALYSIS

3.1 FUNCTIONAL REQUIREMENTS

In software engineering, a functional requirement defines a function of a software system or its component. A function is described as a set of inputs, the behavior, and outputs. Functional requirements may be calculations, technical details, data manipulation and processing and other specific functionality that define what a system is supposed to accomplish. Behavioral requirements describing all the cases where the system uses the functional requirements are captured in use cases.

Here, the system has to perform the following tasks:

 Take user id and password along with secret key, match it with corresponding database entries. If a match is found then continue else raise an error message.  Encrypt the file to form a new encrypted file by using an encryption algorithm.  Must be able to retrieve the original file from the encrypted file using the corresponding decryption algorithm.  If any modification is performed on encrypted file, owner of the file should be notified.

3.2 NON-FUNCTIONAL REQUIREMENTS

In systems engineering and requirements engineering, a non-functional requirement is a requirement that specifies criteria that can be used to judge the operation of a system, rather than specific behaviors. This should be contrasted with functional requirements that define specific behavior or functions. The plan for implementing functional requirements is detailed in the system design. The plan for implementing non-functional requirements is detailed in the system architecture.

Other terms for non-functional requirements are "constraints", "quality attributes", "quality goals", "quality of service requirements" and "non-behavioral requirements". Dept of CSE, NHCE 8

Secure File Transfer Protocol using LibEvent

Some of the quality attributes are as follows:

ACCESSIBILITY:

Accessibility is a general term used to describe the degree to which a product, device, service, or environment is accessible by as many people as possible.

In our project people who have registered with the cloudcan access the cloud to store and retrieve their data with the help of a secret key sent to their email ids. User interface is simple and efficient and easy to use. MAINTAINABILITY:

In software engineering, maintainability is the ease with which a software product can be modified in order to:  Correct defects  Meet new requirements

New functionalities can be added in the project based on the user requirements just by adding the appropriate files to existing project using ASP.net and C# programming languages. Since the programming is very simple, it is easier to find and correct the defects and to make the changes in the project. SCALABILITY:

System is capable of handling increase total throughput under an increased load when resources (typically hardware) are added. System can work normally under situations such as low bandwidth and large number of users. PORTABILITY:

Portability is one of the key concepts of high-level programming. Portability is the software code base feature to be able to reuse the existing code instead of creating new code when moving software from an environment to another.

Dept of CSE, NHCE 9

Secure File Transfer Protocol using LibEvent

Project can be executed under different operation conditions provided it meet its minimum configurations. Only system files and dependant assemblies would have to be configured in such case.

3.3 HARDWARE REQUIREMENTS

Processor : Any Processor above 500 MHz RAM : 512Mb Hard Disk : 10 GB Input device : Standard Keyboard and Mouse Output device : VGA and High Resolution Monitor

3.4 SOFTWARE REQUIREMENTS

• Operating system : Ubuntu Linux • IDE : VI • Languages : gcc (C compiler)

Dept of CSE, NHCE 10

Secure File Transfer Protocol using LibEvent

CHAPTER 4 DESIGN 4.1 LIBEVENT The libevent API provides a mechanism to execute a callback function when a specific event occurs on a file descriptor or after a timeout has been reached. Furthermore, libevent also support callbacks due to signals or regular timeouts. libevent is meant to replace the event loop found in event driven network servers. An application just needs to call event_dispatch() and then add or remove events dynamically without having to change the event loop. Currentlylibeventsupports /dev/poll, (), POSIX select(), Windows select(), poll(), and epoll(). The internal event mechanism is completely independent of the exposed event API, and a simple update of libevent can provide new functionality without having to redesign the applications. As a result, Libevent allows for portable application development and provides the most scalable event notification mechanism available on an operating system. Libevent can also be used for multi-threaded applications, either by isolating each event_base so that only a single thread accesses it, or by locked access to a single shared event_base. Libevent should compile on Linux, *BSD, Mac OS X, Solaris, Windows, and more. Libevent additionally provides a sophisticated framework for buffered network IO, with support for sockets, filters, rate-limiting, SSL, zero-copy file transmission, and IOCP. Libevent includes support for several useful protocols, including DNS, HTTP, and a minimal RPC framework. Libevent is a library for writing fast portable nonblocking IO.

4.2 DESIGN GOALS

Portability A program written using Libevent should work across all the platforms Libevent supports. Even when there is no really good way to do nonblocking IO, Libevent should support the so-so ways, so that your program can run in restricted environments.

Dept of CSE, NHCE 11

Secure File Transfer Protocol using LibEvent

Speed Libevent tries to use the fastest available nonblocking IO implementations on each platform, and not to introduce much overhead as it does so.

Scalability Libevent is designed to work well even with programs that need to have tens of thousands of active sockets.

Convenience Whenever possible, the most natural way to write a program with Libevent should be the stable, portable way.

4.3 LIBRARIES

When Libevent is built, by default it installs the following libraries: libevent_core

All core event and buffer functionality. This library contains all the event_base, evbuffer, bufferevent, and utility functions. libevent_extra

This library defines protocol-specific functionality that you may or may not want for your application, including HTTP, DNS, and RPC. libevent

This library exists for historical reasons; it contains the contents of both libevent_core and libevent_extra. You shouldn’t use it; it may go away in a future version of Libevent. The following libraries are installed only on some platforms:

Dept of CSE, NHCE 12

Secure File Transfer Protocol using LibEvent

libevent_pthreads

This library adds threading and locking implementations based on the pthreads portable threading library. It is separated from libevent_core so that you don’t need to link against pthreads to use Libevent unless you are actually using Libevent in a multithreaded way. libevent_openssl

This library provides support for encrypted communications using buffer events and the OpenSSL library. It is separated from libevent_core so that you don’t need to link against OpenSSL to use Libevent unless you are actually using encrypted connections.

4.4 BENCHMARK

Performance comparison using different event notification mechansims in Libevent. We declare interest in a large number of connections of which most are cold and only a few

are active. The benchmark measures how long it takes to serve one active connection and exposes scalability issues of traditional interfaces like select or poll. The benchmark measures how long it takes to serve one hundred active connections that chain writes to new connections until thousand writes and reads have happened. It exercises the event loop several times.  locking  unlocking  lock allocation  lock destruction

Dept of CSE, NHCE 13

Secure File Transfer Protocol using LibEvent

 Conditions  condition variable creation  condition variable destruction  waiting on a condition variable  signaling/broadcasting to a condition variable  Threads  thread ID detection

4.5 HEADERS

All current public Libevent headers are installed under the event2 directory. Headers fall into three broad classes: API headers

An API header is one that defines current public interfaces to Libevent. These headers have no special suffix. Compatibility headers

A compatibility header includes definitions for deprecated functions. You shouldn’t include it unless you’re porting a program from an older version of Libevent. Structure headers

These headers define structures with relatively volatile layouts. Some of these are exposed in case you need fast access to structure component; some are exposed for historical reasons. Relying on any of the structures in headers directly can break your program’s binary compatibility with other versions of Libevent, sometimes in hard-to- debug ways. These headers have the suffix "_struct.h"

4.6 RECOGNIZED FLAGS

These are the flags you can pass to the flags argument of the evconnlistener_new() function. You can give any number of these:

Dept of CSE, NHCE 14

Secure File Transfer Protocol using LibEvent

LEV_OPT_LEAVE_SOCKETS_BLOCKING

By default, when the connection listener accepts a new incoming socket, it sets it up to be non-blocking so that you can use it with the rest of Libevent. Set this flag if you do not want this behavior. LEV_OPT_CLOSE_ON_FREE

If this option is set, the connection listener closes its underlying socket when you free it.

LEV_OPT_CLOSE_ON_EXEC

If this option is set, the connection listener sets the close-on-exec flag on the underlying listener socket. See your platform documentation for fcntl and FD_CLOEXEC for more information. LEV_OPT_REUSEABLE

By default on some platforms, once a listener socket is closed, no other socket can bind to the same port until a while has passed. Setting this option makes Libevent mark the socket as reusable, so that once it is closed, another socket can be opened to listen on the same port. LEV_OPT_THREADSAFE

Allocate locks for the listener, so that it’s safe to use it from multiple threads. New in Libevent 2.0.8-rc. LEV_OPT_DISABLED

Initialize the listener to be disabled, not enabled. You can turn it on manually with evconnlistener_enable(). LEV_OPT_DEFERRED_ACCEPT

If possible, tell the kernel to not announce sockets as having been accepted until some data has been received on them, and they are ready for reading. Do not use this option if your protocol doesn’t start out with the client transmitting data, since in that case this option will sometimes cause the kernel to never tell you about the connection. Not all operating systems support this option: on ones that don’t, this option has no effect.

Dept of CSE, NHCE 15

Secure File Transfer Protocol using LibEvent

4.7 BUFFEREVENTS: CONCEPTS AND BASICS

Most of the time, an application wants to perform some amount of data buffering in addition to just responding to events. When we want to write data, for example, the usual pattern runs something like:  Decide that we want to write some data to a connection; put that data in a buffer.  Wait for the connection to become writable  Write as much of the data as we can  Remember how much we wrote, and if we still have more data to write, wait for the connection to become writable again. This buffered IO pattern is common enough that Libevent provides a generic mechanism for it. A "bufferevent" consists of an underlying transport (like a socket), a read buffer, and a write buffer. Instead of regular events, which give callbacks when the underlying transport is ready to be read or written, a bufferevent invokes its user-supplied callbacks when it has read or written enough data. There are multiple types of bufferevent that all share a common interface. As of this writing, the following types exist: Socket-based bufferevents

A bufferevent that sends and receives data from an underlying stream socket, using the event_* interface as its backend. Asynchronous-IO bufferevents

A bufferevent that uses the Windows IOCP interface to send and receive data to an underlying stream socket. (Windows only; experimental.) Filtering bufferevents

A bufferevent that processes incoming and outgoing data before passing it to an underlying bufferevent object—for example, to compress or translate data. pairedbufferevents

Two bufferevents that transmit data to one another.

Dept of CSE, NHCE 16

Secure File Transfer Protocol using LibEvent

Bufferevents and evbuffers

Every bufferevent has an input buffer and an output buffer. These are of type "structevbuffer". When you have data to write on a bufferevent, you add it to the output buffer; when a bufferevent has data for you to read, you drain it from the input buffer. The evbuffer interface supports many operations; we discuss them in a later section.

4.8 CALLBACK AND WATERMARKS

Every bufferevent has two data-related callbacks: a read callback and a write callback. By default, the read callback is called whenever any data is read from the underlying transport, and the write callback is called whenever enough data from the output buffer is emptied to the underlying transport. You can override the behaviour of these functions by adjusting the read and write "watermarks" of the bufferevent. Every bufferevent has four watermarks: Read low-water mark

Whenever a read occurs that leaves the bufferevent’s input buffer at this level or higher, the bufferevent’s read callback is invoked. Defaults to 0, so that every read results in the read callback being invoked. Read high-water mark

If the bufferevent’s input buffer ever gets to this level, the bufferevent stops reading until enough data is drained from the input buffer to take us below it again. Defaults to unlimited, so that we never stop reading because of the size of the input buffer. Write low-water mark

Whenever a write occurs that takes us to this level or below, we invoke the write callback. Defaults to 0, so that a write callback is not invoked unless the output buffer is emptied. Write high-water mark

Not used by a bufferevent directly, this watermark can have special meaning when a bufferevent is used as the underlying transport of another bufferevent. See notes on filtering bufferevent’s below. Dept of CSE, NHCE 17

Secure File Transfer Protocol using LibEvent

A bufferevent also has an "error" or "event" callback that gets invoked to tell the application about non-data-oriented events, like when a connection is closed or an error occurs. The following event flags are defined: BEV_EVENT_READING

An event occured during a read operation on the bufferevent. See the other flags for which event it was. BEV_EVENT_WRITING

An event occured during a write operation on the bufferevent. See the other flags for which event it was. BEV_EVENT_ERROR

An error occurred during a bufferevent operation. For more information on what the error was, call EVUTIL_SOCKET_ERROR(). BEV_EVENT_TIMEOUT

A timeout expired on the bufferevent.

BEV_EVENT_EOF

We got an end-of-file indication on the bufferevent.

BEV_EVENT_CONNECTED

We finished a requested connection on the bufferevent.

Deferred callbacks

By default, a bufferevent callbacks are executed immediately when the corresponding condition happens. (This is true of evbuffer callbacks too; we’ll get to those later.) This immediate invocation can make trouble when dependencies get complex. For example, suppose that there is a callback that moves data into evbuffer A when it grows empty, and another callback that processes data out of evbuffer A when it grows full. Since these Dept of CSE, NHCE 18

Secure File Transfer Protocol using LibEvent

calls are all happening on the stack, you might risk a stack overflow if the dependency grows nasty enough. To solve this, you can tell a bufferevent (or an evbuffer) that its callbacks should be deferred. When the conditions are met for a deferred callback, rather than invoking it immediately, it is queued as part of the event_loop() call, and invoked after the regular events' callbacks. BEV_OPT_CLOSE_ON_FREE

When the bufferevent is freed, close the underlying transport. This will close an underlying socket, free an underlying bufferevent, etc. BEV_OPT_THREADSAFE

Automatically allocate locks for the bufferevent, so that it’s safe to use from multiple threads.

BEV_OPT_DEFER_CALLBACKS

When this flag is set, the bufferevent defers all of itscallbacks, as described above.

BEV_OPT_UNLOCK_CALLBACKS

By default, when the bufferevent is set up to be threadsafe, the bufferevent’s locks are held whenever the any user-provided callback is invoked. Setting this option makes Libevent release the bufferevent’s lock when it’s invoking your callbacks.

Dept of CSE, NHCE 19

Secure File Transfer Protocol using LibEvent

CHAPTER 5

IMPLEMENTATION

5.1 CONNECTION OF SFTP By default, SFTP uses the SSH protocol to authenticate and establish a secure connection. Because of this, the same authentication methods are available that are present in SSH. Although passwords are easy to use and set up by default, we recommend you create SSH keys and transfer your public key to any system that you need to access. This is much more secure and can save you time in the long run. Please see this guide to set up SSH keys in order to access your server if you have not done so already. If you can connect to the machine using SSH, then you have completed all of the necessary requirements necessary to use SFTP to manage files. Test SSH access with the following command: ssh username@remote_hostname_or_IP

If that works, exit back out by typing: exit

We can establish an SSH connection and then open up an SFTP session using that connection by issuing the following command: sftp username@remote_hostname_or_IP

You will connect the remote system and your prompt will change to an SFTP prompt.

5.2 EVENT MANAGEMENT Connect event: structevent_base *evloop; struct event connect_event; evloop = event_base_new();

Dept of CSE, NHCE 20

Secure File Transfer Protocol using LibEvent

event_set(&connect_event, sock1, EV_READ | EV_PERSIST, cmd_connect, evloop); event_base_set(evloop, &connect_event);

if(event_add(&connect_event, NULL)) { printf("Error scheduling connection event on the evvent loop.\n"); }

// Start the event loop if(event_base_dispatch(evloop)) { printf("Error running event loop.\n"); }

5.3 Time Event: struct event ev; structtimevaltv;

tv.tv_sec = 600; tv.tv_usec = 0;

event_init(); evtimer_set(&ev, ftimer, NULL); evtimer_add(&ev, &tv); event_dispatch();

5.4 PWD

‘pwd‘ stands for ‘Print Working Directory‘. As the name states, command ‘pwd‘ prints the current working directory or simply the directory user is, at present. It prints the current directory name with the complete path starting from root (/). This command is built in shell command and is available on most of the shell – bash, Bourne shell, ksh,zsh, etc.

Dept of CSE, NHCE 21

Secure File Transfer Protocol using LibEvent

pwd is one of the simplest yet most popular and most widely used command. A good command over pwd is basic to use Linux terminal.

5.5 CD

The cd command, also known as chdir (change directory), is a command-line OS shell command used to change the current working directory in operating systems such as Unix, DOS, OS/2, AmigaOS (where if a bare path is given, cd is implied), Windows, and Linux. It is also available for use in shell scripts and batch files. The system call that effects the command in most operating systems is chdir that is defined by POSIX.

A directory is a logical section of a file system used to hold files. Directories may also contain other directories. The cd command can be used to change into a subdirectory, move back into the parent directory, move all the way back to the root directory or move to any given directory. Consider the following subsection of a Unix file system, which shows a user's home directory (represented as “~”) with a file (“text.txt”) and three subdirectories. DOS maintains separate working directories for each lettered drive, and also has the concept of a current working drive. The cd command can be used to change the working directory of the working drive or another lettered drive. Typing the drive letter as a command on its own changes the working drive, e.g. C:; alternatively, cd with the /d switch may be used to change the working drive and that drive's working directory in one step. Modern versions of Windows simulate this behavior for backwards compatibility under CMD.EXE.

5.6 LS

In computing, ls is a command to list files in Unix and Unix-like operating systems. ls is specified by POSIX and the Single UNIX Specification. When invoked without any arguments, ls lists the files in the current working directory.

Dept of CSE, NHCE 22

Secure File Transfer Protocol using LibEvent

Unix and Unix-like operating systems maintain the idea of a current working directory, that is, where one is currently positioned in the hierarchy of directories. When invoked without any arguments, ls lists the files in the current working directory. A directory that is not the current working directory can be specified and ls will list the files there. The user also may specify any list of files and directories. In this case, all files and all contents of specified directories will be listed. Files whose names start with "." are not listed, unless the -a flag is specified, the -A flag is specified, or the files are specified explicitly. Without options, ls displays files in a bare format. This bare format however makes it difficult to establish the type, permissions, and size of the files. drwxr--r-- 1 fred editors 4096 Mar 1 2007 drafts This means that the letters behind the file descriptor (d), which indicates a folder or 'directory', list three characters to indicate permissions for the owner of 'drafts' (rwx), then the group to which the file belongs (r--), and the rights of others (r--). 'drafts' is a directory (d), the owner of which has the right to read (r) write (w) and execute (x): rwx, group members have (r--), meaning read only, and others have (r--), meaning read only access.

5.7 TIME TO LIVE

Time to live (TTL) or hop limit is a mechanism that limits the lifespan or lifetime of data in a computer or network. TTL may be implemented as a counter or timestamp attached to or embedded in the data. Once the prescribed event count or timespan has elapsed, data is discarded. In computer networking, TTL prevents a data packet from circulating indefinitely. The TTL is set in an eight binary digit field in the packet header by the sending host and is used to prevent packets from endlessly circulating on the Internet or other network. When forwarding an IP packet, routers are required to decrease the TTL by at least one. If a packet's TTL field reached zero, the router detecting it discards the packet and sends an ICMP (Internet control message protocol) message back to the originating host.

Dept of CSE, NHCE 23

Secure File Transfer Protocol using LibEvent

TTLs occurs in the Domain Name System (DNS), where they are set by an authoritative name server for a particular resource record. When a caching (recursive) name server queries the authoritative name server for a resource record, it will cache that record for the time (in seconds) specified by the TTL. If a stub resolver queries the caching name server for the same record before the TTL has expired, the caching server will simply reply with the already cached resource record rather than retrieve it from the authoritative name server again. TTL for NXDOMAIN responses is set from the minimum of the MINIMUM field of the SOA record and the TTL of the SOA itself, and indicates how long a resolver may cache the negative answer. Shorter TTLs can cause heavier loads on an authoritative name server, but can be useful when changing the address of critical services like Web servers or MX records, and therefore are often lowered by the DNS administrator prior to a service being moved, in order to minimize disruptions. The units used are seconds. An older common TTL value for DNS was 86400 seconds, which is 24 hours. A TTL value of 86400 would mean that, if a DNS record was changed on the authoritative name server, DNS servers around the world could still be showing the old value from their cache for up to 24 hours after the change. Newer DNS methods that are part of a DR (Disaster Recovery) system may have some records deliberately set extremely low on TTL. For example, a 300-second TTL would help key records expire in 5 minutes to help ensure these records are flushed quickly worldwide. This gives administrators the ability to edit and update records in a timely manner. TTL values are "per record" and setting this value on specific records is sometimes honored automatically by all standard DNS systems worldwide. However a problem persists in that many caching DNS name servers set their own TTLs regardless of the authoritative records, so it cannot be guaranteed that all downstream DNS servers have the new records after the TTL has expired.

Dept of CSE, NHCE 24

Secure File Transfer Protocol using LibEvent

CHAPTER 6

TESTING

The purpose of testing is to discover errors. Testing is the process of trying to discover every conceivable fault or weakness in a work product. It provides a way to check the functionality of components, sub-assemblies, assemblies and/or a finished product it is the process of exercising software with the intent of ensuring that the Software system meets its requirements and user expectations and does not fail in an unacceptable manner. There are various types of test. Each test type addresses a specific testing requirement. TYPES OF TESTS 6.1 UNIT TESTING Unit testing involves the design of test cases that validate that the internal program logic is functioning properly, and that program inputs produce valid outputs. All decision branches and internal code flow should be validated. It is the testing of individual software units of the application .it is done after the completion of an individual unit before integration. This is a structural testing, that relies on knowledge of its construction and is invasive. Unit tests perform basic tests at component level and test a specific business process, application, and/or system configuration. Unit tests ensure that each unique path of a business process performs accurately to the documented specifications and contains clearly defined inputs and expected results.

6.2 INTEGRATION TESTING Integration tests are designed to test integrated software components to determine if they actually run as one program. Testing is event driven and is more concerned with the basic outcome of screens or fields. Integration tests demonstrate that although the components were individually satisfaction, as shown by successfully unit testing, the combination of components is correct and consistent. Integration testing is specifically aimed at exposing the problems that arise from the combination of components.

Dept of CSE, NHCE 25

Secure File Transfer Protocol using LibEvent

6.3VALIDATIONTESTING

An engineering validation test (EVT) is performed on first engineering prototypes, to ensure that the basic unit performs to design goals and specifications. It is important in identifying design problems, and solving them as early in the design cycle as possible, is the key to keeping projects on time and within budget. Too often, product design and performance problems are not detected until late in the product development cycle — when the product is ready to be shipped. The old adage holds true: It costs a penny to make a change in engineering, a dime in production and a dollar after a product is in the field. Verification is a Quality control process that is used to evaluate whether or not a product, service, or system complies with regulations, specifications, or conditions imposed at the start of a development phase. Verification can be in development, scale- up, or production. This is often an internal process. Validation is a Quality assurance process of establishing evidence that provides a high degree of assurance that a product, service, or system accomplishes its intended requirements. This often involves acceptance of fitness for purpose with end users and other product stakeholders. The testing process overview is as follows:

VALIDATION TESTING

INTEGRATION TESTING

UNIT TESTING

Dept of CSE, NHCE 26

Secure File Transfer Protocol using LibEvent

CHAPTER 7

SNAPSHOTS

7.1 SNAPSHOT OF CLIENT AND SERVER TERMINAL

Dept of CSE, NHCE 27

Secure File Transfer Protocol using LibEvent

7.2 SNAPSHOT OF INVALID PUT COMMAND

7.3 SNAPSHOT OF GET COMMAND AFTER FILE ELAPSED

Dept of CSE, NHCE 28

Secure File Transfer Protocol using LibEvent

7.4 SNAPSHOT OF GET COMMAND

7.5 SNAPSHOT OF CD COMMAND

Dept of CSE, NHCE 29

Secure File Transfer Protocol using LibEvent

7.6 SNAPSHOT OF LS COMMAND

7.7 SNAPSHOT OF PWD COMMAND

Dept of CSE, NHCE 30

Secure File Transfer Protocol using LibEvent

7.8 SNAPSHOT OF QUIT COMMAND

Dept of CSE, NHCE 31

Secure File Transfer Protocol using LibEvent

CHAPTER 8

CONCLUSION AND ENHANCEMENT

8.1 CONCLUSION

In this paper we have worked to facilitate event management to execute based on events. The use of libevent not only makes ftp event based but also in an efficient, fast and reliable manner. The callback approach gives a lot of efficiency and power to the programming structures. As a result, Libevent allows for portable application development and provides the most scalable event notification mechanism available on an operating system. Libevent can also be used for multi-threaded applications, either by isolating each event_base so that only a single thread accesses it, or by locked access to a single shared event_base. Libevent should compile on Linux, *BSD, Mac OS X, Solaris, Windows, and more. Although SFTP is a simple tool, it is very useful for administrating servers and transferring files between them. If you are used to using FTP or SCP to accomplish your transfers, SFTP is a good way to leverage the strengths of both. While it is not appropriate for every situation, it is a flexible tool to have in your repertoire.

8.2 FUTURE ENHANCEMENT

Libevent has long had an "evbuffer" implementation to wrap access to an input or output memory buffer. In previous versions, the implementation was very inefficient and lacked some desirable features. Chunked-memory internal representation

Previously, each evbuffer was a huge chunk of memory. When we ran out of space in an evbuffer, we used realloc() to grow the chunk of memory. When data was misaligned, we used memmove to move the data back to the front of the buffer. Needless to say, this is a terrible interface for networked IO.

Dept of CSE, NHCE 32

Secure File Transfer Protocol using LibEvent

Now, evbuffers are implemented as a linked list of memory chunks, like most Unix kernels use for network IO. Data is added at the end of the linked list and removed from the front, so that we don't ever need realloc huge chunks or memmove the whole buffer contents. To avoid excessive calls to read and write, we use the readv/writev interfaces to do IO on multiple chunks at once with a single system call.

Compatibility Note The evbufferstruct is no longer exposed in a header. The code here is too volatile to expose an official evbuffer structure, and there was never any means provided to create an evbuffer except via evbuffer_new which heap-allocated the buffer. If you need access to the whole bufer as a linear chunk of memory, the EVBUFFER_DATA() function still works. Watch out, though: it needs to copy the buffer's contents in a linear chunk before you can use it.

More flexible readline support The old evbuffer_readline() function (which accepted any sequence of CR and LF characters as a newline, and which couldn't handle lines containing NUL characters), is now deprecated. The preferred function is evbuffer_readln(), which supports a variety of line-ending styles, and which can return the number of characters in the line returned.

Support for file-based IO in evbuffers You can now add chunks of a file into a evbuffer, and Libevent will have your OS use mapped-memory functionality, sendfile, or splice to transfer the data without ever copying it to user space. On OSs where this is not supported, Libevent just loads the data. There are probably some bugs remaining in this code. On some platforms (like Windows), it just reads the relevant parts of the file into RAM.

Dept of CSE, NHCE 33

Secure File Transfer Protocol using LibEvent

Support for zero-copy ("scatter/gather") writes in evbuffers

You can add a piece of memory to an evbuffer without copying it.Instead, Libevent adds a new element to the evbuffer's linked list of chunks with pointer to the memory you supplied. You can do this either with a reference-counted chunk (via evbuffer_add_reference), or by asking Libevent for a pointer to its internal vectors (via evbuffer_reserve_space or evbuffer_peek()).

Multiple callbacks per evbuffer

Previously, you could only have one callback active on an evbuffer at atime. In practice, this meant that if one part of Libevent was using anevbuffer callback to notice when an internal evbuffer was reading or writing data, you couldn't have your own callback on that evbuffer. Now, you can now use the evbuffer_add_cb() function to add a callback that does not interfere with any other callbacks. The evbuffer_setcb() function is now deprecated.

New callback interface Previously, evbuffer callbacks were invoked with the old size of the buffer and the new size of the buffer. This interface could not capture operations that simultaneously filled _and_ drained a buffer, or handle cases where we needed to postpone callbacks until multiple operations were complete. Callbacks that are set with evbuffer_setcb still use the old API. Callbacks added with evbuffer_add_cb() use a new interface that takes a pointer to a struct holding the total number of bytes drained read and the total number of bytes written.

Dept of CSE, NHCE 34

Secure File Transfer Protocol using LibEvent

BIBLIOGRAPHY Good teachers are worth more than thousand books, we have them our department.

TEXT BOOKS: 1. Behrouz A.Forouzan and Richard F.Gilberg: UNIX and ShellProgramming,Cenage Learning,2005 2. Behrouz A.Forouzan,: and Networking,4th Edition Tata McGraw-Hill, 2006 3. Communication Networks –Fundamental Concepts and Keyarchitectures, Alberto Leon Garcia & Indrawidjaja, 2nd Edition, Tata McGraw-Hill, India

SITES REFERED: http://www.libevent.org http://www.tutorialspoint.com http://www.cydrary.it

Dept of CSE, NHCE 35