Monthly Archives: August 2015

How to Convert HTML to PDF in PHP with fpdf

By | August 30, 2015

How to Convert HTML to PDF in PHP with fpdf

HTML to PDF conversion is always a problem for PHP Programmers and all the time they search for suitable solutions so after reviewing this article you will not take more than 10 minutes to configure HTML to PDF, I have used a library fpdf open source and very useful library for developers here is a simple tutorial on how to convert How to Convert HTML to PDF with fpdf.

How to Convert HTML to PDF in PHP with fpdf

 

You have to download fpdf library and  include it in your PHP file below settings and how to show tags, fonts and images in your pdf file. With fpdf library we used HTMLparser library contributed by programmers and all other libraries available here you can download and use as per your requirement.

index.html

In this file I have created a simple contact form data on submit it show that submitted data on PDF format.

actionpdf.php

This file contain PHP code to generate pdf file and show your submitted data on that file.

In this file we add page and auto page break true if your content increase single page area then it will automatically add 2nd page and process.

These lines used to add a logo and select font size for heading.

Select small font then heading for inner content.

That’s all. Have Fun.

Download and Demo links are as:

live_demo_button.fw_ b-download

How to Design CSS Triangle

By | August 27, 2015

Using CSS3 you can design triangles that can be used in Menus, Chat Boxes etc.

Today I am gonna tell you How to Design CSS Triangle .

HTML

You can make them with a single div. It’s nice to have classes for each direction possibility.

CSS

The idea is a box with zero width and height. The actual width and height of the arrow is determined by the width of the border. In an up arrow, for example, the bottom border is colored while the left and right are transparent, which forms the triangle.

Examples:-

css-triangle

PHP 7 – Cool Features that you must know

By | August 25, 2015

Since many years from now, PHP has been regarded as one of the truly brilliant server side scripting languages used for development of websites and web applications. There has a huge collection of PHP versions which have been successful in becoming the best choices of web developers all over the world. The next one to join the group of PHP is PHP 7. With its planned released date approaching at a rapid pace, there have been constant debates regarding the features that would be available with this yet another PHP software version.

PHP 7 – Cool Features that you must know:

PHP 7- Cool Features that you must know

PHP 7- Cool Features that you must know

In this post, I’ll be focusing my attention of some of the features that are expected to arrive with the yet-to-be-released PHP version 7. I’m sure a detailed knowledge about these features would allow you to make the most of PHP for your good. So, let’s learn more about these PHP 7 features.

  1. The problem of Return Types would come to an end

With the release of PHP 7, you’ll now be able to indicate appropriate return types on functions in the form displayed below:

You can specify the return types as int, string, bool etc. The only thing that you need to remember here is hat all you methods and functions which would be returning a specific return type would be unsigned. A possible solution to this is to return instances of wrappers for such kind of values.

 2. The all-new Combined Comparison Operator

Also known as the spaceship operator, the Combined Comparison Operator <=> serves as a brilliant addition to PHP. It works just like strcmp() or the version_compare() functions returning -1 in case the left operand is smaller than the right one, 1 in case the left is greater than the right one and 0 in case both are equal. One of the greatest advantages of Combined Comparison operator is that it can be conveniently used any two operands(floats, integers, arrays etc.) and not just the strings. Have a look at how the Combined Comparison Operator is used in sorting callbacks:

  1. Commendable performance improvements

With key changes being introduced as phpng, PHP 7 will have its performance raised by great bounds and leaps. A majority of smaller hosts would benefit from this increased performance and adopt PHP 7 without giving a second thought. It is expected that PHP 7 will have its performance at par with Facebook HHVM. The only exception being that PHP 7 won’t have a JIT(Just In Time) compiler. Additionally, this new PHP version would also have substantial memory savings.

  1. Changes in terms of Extension APIs

Although the API used for building PHP extensions is still under the refurbishing process, it is subjected to multiple changes. The all new extension API introduced with PHP 7 would be compatible with HHVM run-time as well.

  1. Addition of Abstract Syntax Tree(AST)

As an attempt to bring in the must-needed userland consistency, the PHP web development community has planned to add Abstract Syntax Tree(AST) into the PHP version 7. Serving as an intermediate code representation tool, AST would allow you to eliminate some of the visible inconsistencies in addition to creating room for incredible tooling such as the usage of AST for creating absolutely stunning opcodes.

  1. Introduction of Uniform Variable Syntax

Uniform Variable Syntax plays a pivotal role in solving multiple inconsistencies in the way different expressions are being evaluated. For instance, here is how you can call closures which are already assigned to properties with the help of.

To be more precise, before PHP 7 was being talked about, $obj->$properties[ ‘name’] was used for accessing property which had its name available within the name key of $properties array. Now, with the Universal Variable Syntax, the same would access the name key of the property which has its name housed inside $properties.

That’s it for now!

Conclusion

There’s no doubt that PHP 7 is assumed to be one of the most promising versions of PHP. Now that you know about some of the most impressive features that it has in store for you, it’s time to wait for the ‘Big’ release and take full advantage of PHP for flawless web development.

 

How to Find and Detect IP Address Using Javascript

By | August 24, 2015

How to Find and Detect IP Address Using Javascript

In this short article I will explain how to detect / find the IP Address of the client / user machine using JavaScript & jQuery.

You can use it in several places where you need to store IP Address of Client to Track the Users.

Above I have added an HTML <span> tag which will display the IP Address of the client machine. To get the IP Address I am making a JSON call to the Free Web Servicehttp://jsonip.appspot.com/ and I am passing the name of the callback function which will be called on completion of the request.
When the request is completed the IP address present in the response object is displayed in the HTML <span> tag.
Demo: How to Find and Detect IP Address Using Javascript
live_demo_button.fw_
The above code has been tested in the following browsers.
Internet Explorer  FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.

How To Hack WPA/WPA2 Wi-Fi Using Kali Linux

By | August 24, 2015

Kali Linux can be used for many things, but it probably is best known for its ability to penetration test, or “hack,” WPA and WPA2 networks. There are hundreds of Windows applications that claim they can hack WPA; don’t get them! They’re just scams, used by professional hackers, to lure newbie or wannabe hackers into getting hacked themselves. There is only one way that hackers get into your network, and that is with a Linux-based OS, a wireless card capable of monitor mode, and aircrack-ng or similar. Also note that, even with these tools, Wi-Fi cracking is not for beginners. Playing with it requires basic knowledge of how WPA authentication works, and moderate familiarity with Kali Linux and its tools, so any hacker who gains access to your network probably is no beginner!

How To Hack WPA/WPA2 Wi-Fi Using Kali Linux

These are things that you’ll need:

  1. A successful install of Kali Linux (which you probably already have done).
  2. A wireless adapter capable of injection/monitor mode, here is a list of the best.
  3. A wordlist to try and “crack” the handshake password once it has been captured.
  4. Time and patients

If you have these then roll up your sleeves and let’s see how secure your network is!

Important notice: Hacking into anyone’s Wi-Fi without permission is considered an illegal act or crime in most countries. We are performing this tutorial for the sake of penetration testing, hacking to become more secure, and are using our own test network and router. We are not responsible for what you do with this tutorial. This is for only Educational Purpose.

Step One:

Start Kali Linux and login, preferably as root.

hackiing wifi

 

Step Two:

Plugin your injection-capable wireless adapter, (Unless your computer card supports it). If you’re using Kali in VMware, then you might have to connect the card via the imageicon in the device menu.

Step Three:

Disconnect from all wireless networks, open a Terminal, and type airmon-ng

hacking wifi

 

This will list all of the wireless cards that support monitor (not injection) mode. If no cards are listed, try disconnecting and reconnecting the card and check that it supports monitor mode. You can check if the card supports monitor mode by typing ifconfig in another terminal, if the card is listed in ifconfig, but doesn’t show up in airmon-ng, then the card doesn’t support it.
You can see here that my card supports monitor mode and that it’s listed as wlan0.

Step Four:

Type airmon-ng start followed by the interface of your wireless card. mine is wlan0, so my command would be: airmon-ng start wlan0

Step-4_thumb1

 

The “(monitor mode enabled)” message means that the card has successfully been put into monitor mode. Note the name of the new monitor interface, mon0.


EDIT:
A bug recently discovered in Kali Linux makes airmon-ng set the channel as a fixed “-1” when you first enable mon0. If you receive this error, or simply do not want to take the chance, follow these steps after enabling mon0:

Type: ifconfig [interface of wireless card] down and hit Enter.
Replace [interface of wireless card] with the name of the interface that you enabled mon0 on; probably called wlan0. This disables the wireless card from connecting to the internet, allowing it to focus on monitor mode instead.
After you have disabled mon0 (completed the wireless section of the tutorial), you’ll need to enable wlan0 (or name of wireless interface), by typing: ifconfig [interface of wireless card] up and pressing Enter.



Step Five:

Type airodump-ng followed by the name of the new monitor interface, which is probably mon0.

hacknig wifi

 

If you receive a “fixed channel –1” error, see the Edit above.

Step Six:

Airodump will now list all of the wireless networks in your area, and lots of useful information about them. Locate your network or the network that you have permission to penetration test. Once you’ve spotted your network on the ever-populating list, hit Ctrl + Con your keyboard to stop the process. Note the channel of your target network.

hacking wifi

 

Step Seven:

Copy the BSSID of the target network.

hacking wifi

 

Now type this command:
airodump-ng -c [channel] –bssid [bssid] -w /root/Desktop/ [monitor interface]
Replace [channel] with the channel of your target network. Paste the network BSSID where [bssid] is, and replace [monitor interface] with the name of your monitor-enabled interface, (mon0).

A complete command should look like this:
airodump-ng -c 10 –bssid 00:14:BF:E0:E8:D5 -w /root/Desktop/ mon0

image_thumb[9]

 

Now press enter.

Step Eight:

Airodump with now monitor only the target network, allowing us to capture more specific information about it. What we’re really doing now is waiting for a device to connect or reconnect to the network, forcing the router to send out the four-way handshake that we need to capture in order to crack the password.
Also, four files should show up on your desktop, this is where the handshake will be saved when captured, so don’t delete them!

But we’re not really going to wait for a device to connect, no, that’s not what impatient hackers do. We’re actually going to use another cool-tool that belongs to the aircrack suite called aireplay-ng, to speed up the process. Instead of waiting for a device to connect, hackers use this tool to force a device to reconnect by sending deauthentication (deauth) packets to the device, making it think that it has to reconnect with the router.

Of course, in order for this tool to work, there has to be someone else connected to the network first, so watch the airodump-ng and wait for a client to show up. It might take a long time, or it might only take a second before the first one shows. If none show up after a lengthy wait, then the network might be empty right now, or you’re to far away from the network.

You can see in this picture, that a client has appeared on our network, allowing us to start the next step.

hacking wifii

 

Step Nine:

leave airodump-ng running and open a second terminal. In this terminal, type this command:
aireplay-ng –0 2 –a [router bssid] –c [client bssid] mon0
The –0 is a short cut for the deauth mode and the 2 is the number of deauth packets to send.
-a indicates the access point (router)’s bssid, replace [router bssid] with the BSSID of the target network, which in my case, is 00:14:BF:E0:E8:D5.
-c indicates the clients BSSID, noted in the previous picture. Replace the [client bssid] with the BSSID of the connected client, this will be listed under “STATION.”
And of course, mon0 merely means the monitor interface, change it if yours is different.

My complete command looks like this:
aireplay-ng –0 2 –a 00:14:BF:E0:E8:D5 –c 4C:EB:42:59:DE:31 mon0

hacking wifi

 

Step Ten:

Upon hitting Enter, you’ll see aireplay-ng send the packets, and within moments, you should see this message appear on the airodump-ng screen!

image_thumb5

 

step-10_thumb2

 

This means that the handshake has been captured, the password is in the hacker’s hands, in some form or another. You can close the aireplay-ng terminal and hit Ctrl + C on the airodump-ng terminal to stop monitoring the network, but don’t close it yet just incase you need some of the information later.

Step 11:

This concludes the external part of this tutorial. From now on, the process is entirely between your computer, and those four files on your Desktop. Actually, the .cap one, that is important. Open a new Terminal, and type in this command:
aircrack-ng -a2 -b [router bssid] -w [path to wordlist] /root/Desktop/*.cap

-a is the method aircrack will use to crack the handshake, 2=WPA method.
-b stands for bssid, replace [router bssid] with the BSSID of the target router, mine is 00:14:BF:E0:E8:D5.
-w stands for wordlist, replace [path to wordlist] with the path to a wordlist that you have downloaded. I have a wordlist called “wpa.txt” in the root folder.
/root/Desktop/*.cap is the path to the .cap file containing the password, the * means wild card in Linux, and since I’m assuming that there are no other .cap files on your Desktop, this should work fine the way it is.

My complete command looks like this:
aircrack-ng –a2 –b 00:14:BF:E0:E8:D5 –w /root/wpa.txt  /root/Desktop/*.cap

image_thumb[3]

 

Now press Enter.

Step 12:

Aircrack-ng will now launch into the process of cracking the password. However, it will only crack it if the password happens to be in the wordlist that you’ve selected. Sometimes, it’s not. If this is the case, then you can congratulate the owner on being “Impenetrable,” of course, only after you’ve tried every wordlist that a hacker might use or make!

Cracking the password might take a long time depending on the size of the wordlist. Mine went very quickly.

If the phrase is in the wordlist, then aircrack-ng will show it too you like this:

image_thumb[5]

 

The passphrase to our test-network was “notsecure,” and you can see here that aircrack found it.

If you find the password without a decent struggle, then change your password, if it’s your network. If you’re penetration testing for someone, then tell them to change their password as soon as possible.

Please use this information only in legal ways.

so no you know How To Hack WPA/WPA2 Wi-Fi Using Kali Linux.

Denial Of Service Attacks Using Kali Linux

By | August 22, 2015

Denial Of Service Attacks Using Kali Linux

Just like most other things associated with hacking, a denial of service attack is not everyone’s cup of tea. It, however, can be understood if explained properly. In this tutorial, I’ll try to give you a big picture of denial of service attacks, before I start using geeky terms like packets and all that. We’ll start at the easiest point.

What effect does a denial of service attack have

Wireless hacking usually gives you the password of a wireless network. A man in the middle attack lets you spy on network traffic. Exploiting a vulnerability and sending a payload gives you access and control over the target machine. What exactly does a Denial of Service (DOS) attack do? Basically, it robs the legitimate owner of a resource from the right to use it. I mean if I successfully perform a DOS on your machine, you won’t be able to use it anymore. In the modern scenario, it is used to disrupt online services. Many hacktivist groups (internet activists who use hacking as a form of active resistance – a name worth mentioning here is Anonymous) do a Distributed Denial of service attack on government and private websites to make them listen to the people’s opinion (the legitimacy of this method of dictating your opinion has been a topic of debate, and a lot of hactivists had to suffer jailtime for participating in DDOS). So basically it’s just what its name suggests, Denial Of Service.

Access denied stamp

Basic Concept

It uses the fact that while a service can be more than sufficient to cater to the demands of the desired users, a drastic increase in unwelcome users can make the service go down. Most of us use the words like “This website was down the other day” without any idea what it actually means. Well now you do. To give you a good idea of what is happening, I’ll take the example from the movie “We Are Legion”.

Scenario One : Multiplayer online game

Now consider you are playing an online multi-player game. There are millions of other people who also play this game. Now there’s a pool in the game that everyone likes to visit. Now you and your friends know that they have the power of numbers. There are a lot of you, and together you decide to make identical characters in the game. And then all of you go and block the access to the pool. You just carried out a denial of service attack. The users of the game have now been deprived of a service which they had obtained the right to use when they signed up for the game. This is just what the guys at 4chan (birthplace and residence of Anonymous) did a long time ago. This is the kind of thing that gives you a very basic idea what a denial of service attack can be.
Game They made a Swastika and blocked access to the pool

Scenario 2 : Bus stop

Now assume that due to some reason, you want to disrupt the bus service of your city and stop the people from using the service. To stop the legitimate people from utilizing this service, you can call your friends to unnecessarily use it. Basically you can invite millions of friends to come and crowd around all the bus stops and take the buses without any purpose. Practically it is not feasible since you don’t have millions of friends, and they are definitely not wasting their time and money riding aimlessly from one place to another.
So while this may seem impossible in the real world, in the virtual world, you can cause as much load as a thousand (or even a million) users alone at the click of a button. There are many tools out there for this purpose, however, you are not recommended to use them as a DOS on someone else is illegal, and easy to detect (Knock, knock. It’s the police). We will, come back to this later, and do a DOS on our own computer.

How denial of service attacks are carried out

Basically, when you visit a website, you send them a request to deliver their content to you. What you send is a packet. Basically, it take more than just one packet, you need a lot of them. But still, the bandwidth that you consume in requesting the server to send you some data is very little. In return, the data they send you is huge. This takes up server resources, for which they pay for. A legitimate view can easily earn more than the server costs on account of advertisements, etc. So, companies buy server that can provide enough data transfer for its regular users. However, if the number of users suddenly increases, the server gives up. It goes down. And since the company knows it under DOS, it just turns off the server, so that it does not have to waste its monetary resources on a DOS, and wait till the DOS stops. Now with the modern computers and bandwidth, we alone can easily pretend to be a thousand or even more users at once. While this is not good for the server, it is not something that can make it succumb (your computer is not the only thing that gets better with time, the servers do too). However, if a lot of people like you do a DOS attack, it becomes a distributed denial of service attack. This can easily be fatal for a server. It’s just like you go to a page, and start refreshing it very fast, maybe a thousand times every second. And you are not the only one. There are thousand others that are doing the same thing. So basically you guys are equivalent to more than a million users using the site simultaneously, and that’s not something the server can take. Sites like Google and Facebook have stronger servers, and algorithms that can easily identify a DOS and block the traffic from that IP. But it’s not just the websites that get better, and the black hat hackers too are improving every day. This leaves a huge scope for understanding DOS attacks and becoming an asset to one of these sides ( the good, the bad and the ugly).

A Live DOS on your Kali Machine

If you have Kali linux (The hackers OS- the OS of choice if you use this blog) the here’s a small exercise for you.
We are going to execute a command in the Kali linux terminal that will cripple the operating system and make it hand. It will most probably work on other linux distributions too.
Warning : This code will freeze Kali linux, and most probably it will not recover from the shock. You’ll lose any unsaved data. You will have to restart the machine the hard way (turn of the virtual machine directly or cut the power supply if its a real machine). Just copy paste the code and your computer is gone.

Capture

The machine froze right after I pressed enter. I had to power it off from the Vmware interface.

Capture (1)

What basically happened is that the one line command asked the operating system to keep opening process very fast for an infinite period of time. It just gave up.
Here’s something for the Windows Users

Crashing Windows Using Batch file

Open a notepad. Put the following code in it-

Save the file as name.bat
Bat here is batch file extension. Run it. Game over.
It basically executes the second line, and the third line makes it go over to the first, execute the second, and then over to first again, execute the second….. infinitely. So again, denial of service. All the processing power is used by a useless command, while you, the legitimate user, can’t do anything.
That’s it for this tutorial, we’ll discuss the technical details of a practical denial of service in a later tutorial.

PS:
As suggested in the comments, this script will crash windows much faster-

If you look at the script carefully, it is quite easy to understand what it does. Everytime the script is executed, it does two things-

  1. Opens another instance of the same script
  2. Goes to the beginning of the script
So for every execution, the number of scripts slowing down your computer doubles up. This means that instead of linear, the load on memory and processor is now exponential (the script gets more and more dangerous with time).

 

 

Google Charts with Jquery Ajax

By | August 21, 2015

If you are working for analytics project, you need a rich chart system to display big data results. Google is providing us a powerful chart tools that you can implement charts very simple, this tutorial will explain you how to implement Google charts with Jquery ajax JSON data. Try out there are many free interactive charts and data tools, take a quick look at this live demo.

googlecharts.001

 

 

JavaScript
Here you can replace API url, this demo is working with sample world population density.

Google Charts
Here data object is referees to ajax JSON result.

HTML Code
Charts will display based on DIV id.

JSON
World population density sample JSON data.

Chart Options
There any my options for charts, you can customize the chart colors, titles and 3D view etc..

ajax_data.js
Jquery ajax method for common use.

That’s All. Now you know how to implement Google Charts with Jquery Ajax.

Download and Demo links are as:

 

live_demo_button.fw_b-download

Video & Parallax Backgrounds For Visual Composer v3.4.1

By | August 18, 2015

Video-Parallax-Backgrounds-For-Visual-Composer-v3.4.1

 

Video & Parallax Backgrounds For Visual Composer v3.4.1  allows you to easily add image parallax scrolling effects and video backgrounds to yourWordPress site. The plugin integrates straight into Visual Composer’s row settings, and is flexible to suit your theme’s design.

Just activate the plugin into your WordPress theme and video & parallax background images will become available for Visual Composer rows. Create normal or full-width image parallax backgrounds and even video backgrounds.

Demo and Downloads links for Video & Parallax Backgrounds For Visual Composer v3.4.1 are as:

 

live_demo_button.fw_b-download

 

 

Visual Composer v4.4.2 – Page Builder for WordPress

By | August 18, 2015

Visual-Composer-v4.4.2-Page-Builder-for-WordPress

 

Visual Composer v4.4.2 – Page Builder for WordPress  is drag and drop frontend and backend page builder plugin that will save you tons of time working on the site content. You will be able to take full control over your WordPress site, build any layout you can imagine – no programming knowledge required. Moreover, now you can choose either work on a backend or move your page building process to frontend and instantly see changes you make.
28.01.2015 – ver 4.4.2
– Extra CSS class can be used in grid elements now
– Single image styles fixed
– added action “vc_load_default_templates_action”
– vc_add_default_templates() fixed
– Added compatibility for older Layer slider
– Background disappearing in row on child element deleting fixed
– Message box backwards compatibility added
– Grid builder ajax stability improved
– Css tpl for Design options regenerated
– Custom query in Grid builder handles correctly ampersand and quote marks
– Compatibility with jwplayer improved
– Compatibility with ACF improved

Demo and Dwonload Links for Visual Composer v4.4.2 – Page Builder for WordPress are as:

 

live_demo_button.fw_b-download

Multi-User Video Conference with WebRTc AngularJs & Yeoman

By | August 18, 2015

his is a tutorial for how to implement a Multi-User Video Conference with WebRTc  AngularJs & Yeoman.  It also includes a detailed explanation of how WebRTC works, how the peer to peer connections are being established and how the ICE (Interactive-Connectivity Establishment) framework is used for NAT traversal.

You can find deployed version of the project, we’re going to take a look at in this tutorial, at Heroku, the source code can be found at GitHub.

Why I chose Yeoman and AngularJS?

Yeoman’s generators can handle very quickly all the boilerpates required for the application. Yeoman creates a Grunt build configuration, which allows you to deploy well optimized application with only a few lines of bash:

 

 

Why AngularJS? Well, AngularJS comes with out-of-the-box router (if you use the module angular-route), with well defined components, which enforce the separation of concerns principle and nice data-binding mechanism.

Can I use something else, instead of AngularJS? Yes, sure you can. For such single-page applications, with highly intensive DOM manipulations and limited amount of views (which I call vertical single-page applications), I’d recommend React.js or WebComponents.

webrtc-yeoman

 

WebRTC intro

In my blog post “WebRTC chat with React.js” I already did a brief introduction about what WebRTC is and how it works:

RTC stands for Real-Time Communication. Until browsers implemented WebRTC our only way to provide communication between several browsers was to proxy the messages via a server between them (using WebSockets or HTTP). WebRTC makes the peer-to-peer communication between browsers possible. Using the NAT traversal framework – ICE, we are able find the most appropriate route between the browsers and make them communicate without mediator. Since 1st of July 2014, v1.0 of the WebRTC browser APIs standard is already published by W3C.

In the previous article we used Peer.js in order to open data channel between the peers, who participate in the chat room.

This time we’ll use the plain browser WebRTC API and I’ll explain in a little bit deeper details how a WebRTC session is being established. If you don’t aim deep technical understanding you can skip this section and go directly to the server’s implementation.

How WebRTC works?

Now let’s take a look at the following UML sequence diagram:

sequence-webrtc

 

In the sequence diagram above we’re following how Alice establishes peer connection with Bob, through the application server in the middle (Web App).

  1. Initially Alice calls Bob, through the application server (Web App), for example by invoking a RESTful method (POST /call/Bob).
  2. Through a push notification the application server tells Bob that Alice is calling him. The Web Appmay use WebSockets and send a notification to Bob about Alice‘s call.
  3. Bob response to the push notification and states that he wants to talk with Alice.
  4. The Web App redirects Bob‘s response to Alice.
  5. Once Alice knows that Bob accepted her call, she starts the ICE candidates gathering process. We’ll take a further look at it in the section below.
  6. Once Alice has a set of ICE candidates (we can think of them as pairs – host:port, for example 127.0.0.1:5545, 192.168.0.112:6642, 94.23.24.56:6655, more accuratelya=candidate:1 1 UDP 2130706431 192.168.1.102 1816 typ host), she prepares a SDP offer, which includes the ICE candidates and some additional information (like supported video/audio codecs, etc.). Alicesends this offer to Bob, via the Web App.
  7. The Web App redirects Alice‘s offer to Bob.
  8. Bob gathers his own ICE candidates.
  9. Bob prepares SDP answer (similar to the SDP offer by Alice) and sends it back to Alice, via theWeb App (note that Alice and Bob still cannot establish p2p connection).
  10. Web App redirects Bob‘s response to Alice.
  11. Alice and Bob try to establish p2p connection through the ICE candidates they already have. During this phase more ICE candidates may come up.
    • Alice and Bob make the Cartesian product of the ICE candidates they already have, i.e. Bobcombines all the candidates he have received by Alice with his own candidates, prioritize them and tries to establish connection between them.

If Alice and Bob are not able to establish p2p connection using the ICE candidates they already have, it is very likely they both to be behind symmetric NATs. In this case, if we have provided a TURN server, the video/audio connection will be relayed through it, otherwise they won’t be able to initiate connection between each other.

ICE gathering process

When we use the browser’s WebRTC API for creating a new RTCPeerConnection, we provide a config object. It contains a set of STUN and TURN servers:new RTCPeerConnection({ 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }]}).

In order to understand how we use STUN, you first have to be aware of why we need it. First, lets take a look at what NAT is:

NAT

Before we continue with the tutorial, lets say a few words about what NAT is. NAT stands for Network Address Translation. It is quite common way for translating internal (private) IP addresses to public ones and vice verse. A lot of ISP providers with limited capacity of public IP addresses uses this way of scaling using private IP addresses in their internal networks and translating them to public addresses visible to the outside world. More about NAT and the different types of NAT could be read in this wiki article.

When given host is behind NAT it doesn’t has a public IP address. This means that its IP address looks something like 192.168.0.102. When given host wants to reach a service, outside the local network, it makes a request through the NAT server. The NAT server “translates” the request by changing the source address to the IP address of the NAT server and redirects the request to the destination. The NAT also creates a mapping in the NAT table, which maps the source address (host name and port) to the translated address (host name of the NAT and port assigned for the given request). Once the NAT receives a response by the remote service it uses the NAT table to find the initial source of the request and redirects the response to it.

STUN

So why we would need the STUN servers and what actually are they? Before answering these questions lets answer another one “How we can understand whether we’re behind a NAT or not?”.

Let’s suppose we’re behind a NAT and we want to reach a remote service. If we make a request to the service and the service response us with the source address of the request we can compare it with the address of our machine. If they differ we’re obviously behind a NAT. Note that the service must be located outside of our local network(s).

How we can be sure whether the received address by the service’s response is the one of the NAT directly above us? We can’t. In case of nested NATs we might be behind a few NATs but basically the NAT traversal procedure of ICE remains the same.

The service, which response us with the address of the source of the request is what STUN does. Now when we have the IP address of the NAT we can use a new ICE candidate called reflexive ICE candidate, with value the IP address and port, which the NAT server used in the network address translation.

Implementation

As next step lets take a look at our sample application’s implementation. The application has two main components:

  • back-end – the application server, which is responsible for the communication between the different peers until a p2p connection is established (the Web App from the sequence diagram above)
  • web app – the AngularJS application, which is the actual multi-user video chat (Alice and Bob from the sequence diagram above are two different instances of this application)

You can try the application at Heroku.

Back-end

In this section we will implement our back-end. The back-end is the Web App component from the sequence diagram above. Basically it’s main functionality is to provide static files (htmls, js, css) and to redirect requests by the peers.

This component will maintain a collection of rooms, to each room we will have associated collection ofsocket.io sockets of the peers connected to the given room.

In order to implement the whole functionality of our WebRTC application with JavaScript we can use Node.js for our back-end.

So let’s begin!

Inside the file called index.js in the root add the following content:

Inside the root of your app, invoke the following commands, in order to install the required dependencies:

Now go to lib:

And create a file called server.js. It should has the following content:

Now let’s take a look at the code above step-by-step:

In the snippet above we require all dependencies and configure the created express app to use a directory for providing static files. This directory is located inside a directory called public, which is in the root of our app.

We start the HTTP server and attach socket.io to it (decorate it with socket.io). The connection event insocket.io means that client has connected to our server. Once we have such connection established we need to attach the corresponding event handlers:

These are the three events we’re going to handle. The init event is used for initialization of given room. If the room is already created we join the current client to the room by adding its socket to the collection of sockets associated to the given room (rooms[room_id] is an array of sockets). If the room is not created we create the room and add the current client to it. We generate room randomly using node-uuid module:

One more detail is that when a client connects to given room we notify all other peers associated to the room about the newly connected peer.

We also have a callback (fn), which we invoke with the client’s ID and the room’s id, once the client has successfully connected.

The msg event is an SDP message or ICE candidate, which should be redirected from specific peer to another peer:

The id of given peer is always an integer so that’s why we parse it as first line of the event handler. After that we emit the message to the specified peer in the to property of the event data object.

The last event handler (and last part of the server) is the disconnect handler:

Once given peer disconnects from the server (for example the user close his or her browser or refresh the page), we remove its socket from the collection of sockets associated with the given room (the delete operator usage). After that we emit peer.disconnected event to all other peers in the room, with the id of the disconnected peer. This way all peers connected to the disconnected peer will be able to remove the video element associated with the disconnected client.

The last part of the back-end is the configuration. Inside the root create a directory called config:

Create a file called config.json and set the following content:

Web client

Setup

In order to create a new application using AngularJS’ Yeoman generator you can follow these steps:

You’ll be asked a few questions, answer them as follows:

setup

 

Basically, we only need angular-route as dependency and since we want our application to look relatively well designed with little amount of effort we require Bootstrap as well.

Implementation

As first step, we need to handle some browser inconsistencies. Inside public/app/scripts, create a file calledadapter.js and add the following content inside it

Since Firefox and Chrome still support the WebRTC API with moz and webkit prefixes, we need to take care of it.

Great! So far our future app will work on Chrome and Firefox!

Now lets create a service, called VideoStream, which is responsible for providing us a media stream to the other components in the application:

And lets edit its content:

VideoStream uses $q in order to provide a video stream using getUserMedia. Once we invoke getUserMediathe browser will ask the user for permissions over his/her microphone and web cam:

webcam-permissions

 

After we gain access to the video stream we cache it inside the stream variable, in order to not ask the user for web camera permissions each time we want to access it.

Application configuration

Now it’s time to configure the routes in our application. Editpublic/app/scripts/app.js and add the following route definition:

Here we define two routes:

  • /room – for users accessing the application for first time (without having link to a specific room). They will visit /room and after allowing access to their web cam (because of logic inside RoomCtrl), they will automatically create a new room and will be redirected to another URL (/room/:roomId). Once they are redirected to this URL they can share it with other users they want to talk with.
  • /room/:roomId – users who have already created room can share their URL with other users, who can join the video call.

Of course, if you guess the URL of another users’ session you can join their video call without much effort, for the sake of simplicity we’ve used this simple (and not secure) mechanism. Be polite and do not violate other users’ privacy. :-)

Add this constant definition in the bottom of app.js:

We will use this constant in order connect socket.io client with the server.

Io

Now lets create one more service called Io.

Inside /public/app/scripts/services/io.js set the following content:

Basically here we wrap io inside a service, in order to allow the users to inject it, instead of using the global io. This will allow us to mock io easily instead of monkey patching it, when we want to write tests.

RoomCtrl

Now lets create a new controller, called RoomCtrl:

Edit /public/app/scripts/controllers/room.js:

Now lets look at the code step-by-step:

RoomCtrl accepts as dependencies the following components:

  • $sce – used for setting the source of the video elements
  • VideoStream – used for getting the video stream from the user’s camera
  • $location – used for redirecting the user to the room’s URL
  • $routeParams – used for getting the room id
  • $scope – used for attaching data to it in order to achieve data-binding with the view
  • Room – service which we are going to define next. It is used for managing the peer connections.

In the snippet above we check whether WebRTC is supported. If it isn’t we simply set content of the$scope.error property and stop the controller execution.

VideoStream.get() returns a promise, which once resolved gives us the media stream of the user. When the promise is resolved we initialize the Room passing the stream as argument. In order to visualize the video captured by our web cam we use URL.createObjectURL, to be able to set it as src of a video element in our HTML.

As next step we check whether the roomId is provided. If it is provided we simply join the room with the associated roomId: Room.joinRoom($routeParams.roomId);, otherwise we create a new room. Once the room is created we redirect the user to the room’s URL.

The rest of the RoomCtrl is handling two events:

  • peer.stream – a peer stream is received. Once we receive a new peer stream we add it to the array$scope.peers, which is visualized on the page. The markup on the page maps each stream to a video element.
  • peer.disconnected – once a peer disconnects the peer.disconnected event is being fired. When we receive this event we can simply remove the disconnected peer from the collection.

Room service

The last component from our application is the Room service:

Edit the file /public/app/scripts/services/room.js and set the following content:

Room accepts the following dependencies:

  • $rootScope – it is used in order to invoke the $digest loop, once socket.io event is received. Since the socket.io event handlers are not wrapped inside $scope.$appy we need to invoke $digestmanually.
  • $q – in order to provide promise based interface
  • Io – the wrapped socket.io global function
  • config – the configuration constant we defined in app.js.

Room provides the following public API:

As described above joinRoom is used for joining already existing rooms, createRoom is used for creating new rooms and init is used for initializing the Room service.

The socket.io events handled in this service are:

  • peer.connected – fired when new peer joins the room. Once this event is fired we initiate new SDP offer to this peer
  • peer.disconnected – fired when peer disconnects
  • msg – fired when new SDP offer/answer or ICE candidate are received

Lets take a look at how new offer is being initiated, when a peer connects the room:

Once new peer joins the room makeOffer is invoked with the peer’s id. The first thing we do is togetPeerConnection. If connection with the specified peer id already exists getPeerConnection will return it, otherwise it will create a new RTCPeerConnection and attach the required event handlers to it. After we have the peer connection we invoke the createOffer method. This method will make a new request to the provided STUN server in the RTCPeerConnection configuration and will gather the ICE candidates. Based on the ICE candidates and the supported codecs, etc. it will create a new SDP offer, which we will send to the server. As we saw above the server will redirect the offer to the peer pointed by the property to of the event object.

Now lets take a look at the handler of the msg message:

Here we directly invoke handleMessage, so lets trace the function’s implementation:

In the first line we get the peer connection with the peer with id pointed by the by property. Once we get the connection we switch through the different message types:

  • sdp-offer – if we receive this message, this means that we have just connected to the room and the rest of the peers inside this room want to initiate new peer connection with us. In order to answer them with our ICE candidates, video codecs, etc. we create a new answer using createAnswer but before that we setRemoteDescription (the description of the remote peer). Once we prepare the SDP answer we send it to the appropriate peer via the server.
  • sdp-answer – if we receive SDP answer by given peer, this means that we have already sent SDN offer to this peer. We set the remote description and we hope that we’ll successfully initiate the media connection between us (we hope we’re not both behind symmetric NATs).
  • ice – if in the process of negotiation new ICE candidates are being discovered the RTCPeerConnectioninstance will trigger onicecandidate event, which will redirect new msg message to the peer with whom we’re currently negotiating. We simply add the ICE candidate to the appropriate peer connection using the addIceCandidate method.

The last method we’re going to take a look at, in this tutorial, is getPeerConnection:

This method uses peerConnections object, which creates a mapping between peer id and RTCPeerConnectionobject. Initially we check whether we have associated peer connection to the given id, if we do we simply return it. If we don’t have such peer connection we create a new one, we add the event handlersonicecandidate and onaddstream, we cache it and we return it.

Once onaddstream is triggered, this means that the connection was successfully initiated. We can triggerpeer.stream event and later visualize it in a video element on the page.

videoPlayer

This is the last component in our application. Create it using:

Inside public/app/scripts/directives/videoplayer.js set the following content:

Conclusion

Now lets make a retrospective of the solution provided above.

Full-mesh limitations

As you can experience from the tutorial’s demo, the application works effectively with less than 10 users (or even 5, depending on your network bandwidth capacity and CPU).

This is limitation of the full-mesh topology. When we have session with n peers each of these n peers should establish n-1 RTCPeerConnection with the other peers in the room. This means that his video stream will be encoded n-1 times and will be sent n-1 times through the network. This is very inefficient and is almost impractical in production, when communication between multiple parties is required. Solution for this problem is the usage of WebRTC gateway. There are a few open-source projects which solve this issue:

  • Jitsi Videobridge – Jitsi’s team have build a WebRTC compatible video bridge, which uses XMPP Jingle for signaling and Colibri (XMPP extension created by the Jitsi’s team) for establishment of connection with the bridge. The bridge provides audio mixing with very high quality and only forwards the video, which makes it very effective when using a cheap hardware with low computational power.
  • licode – another open-source project, which provides video and audio mixing and custom JSON based protocol for signaling. The last time I tried to use it, its mixing wasn’t with very high quality, in case of background sound the audio connection was almost impossible to use.

Signaling protocol

In this tutorial we used custom JSON protocol for signaling. Better choice will be to use standardized protocol, such as XMPP Jingle or SIP. This will allow you better flexibility in case you need to integrate your service with other, already existing services.

More

There are a plenty of other topics we didn’t cover but they are unfortunately outside the scope of this tutorial. If you’re interested in further reading you can check out the resources below or ping me for additional information.

Resources