Rust – How to read all the data of a TcpStream (socket) completely ?

Hi everyone. I have started learning Rust and I tried creating a project RServer which is an app for intercepting/capturing TCP requests sent by browser and other apps running on a system. While developing RServer , I faced an issue while trying to read the complete data from a TcpStream struct. TcpStream has only read method , but socket /TCP streams constructs do not have method such as read_all to read all the data from the stream. In this post, I am going to share my technique which I used in RServer .

As we do not have any built-in method to read the TcpStream completely in one go , we obviously need to use some kind of loop to read the complete data from a given stream. Let us consider that we want to read all the data and we need to return the data and its length/size.

/// Read the stream data and return stream data & its length
fn read_stream(stream: &mut TcpStream) -> (Vec, usize) {
    let buffer_size = 512;
    let mut request_buffer = vec![];
    // let us loop & try to read the whole request data
    let mut request_len = 0usize;
    loop {
        let mut buffer = vec![0; buffer_size];
        match stream.read(&mut buffer) {
            Ok(n) => {
               
                if n == 0 {
                    break;
                } else {
                    request_len += n;

                    // we need not read more data in case we have read less data than buffer size
                    if n  {
                println!("Error in reading stream data: {:?}", e);
                break;
            }
        }
    }

    (request_buffer, request_len)
}

Explanation :

I have taken an initial buffer size as 512 as an example, we will be reading 512 bytes or lesser in one go from the stream. I have taken a mutable Vector here as we cannot determine the TcpStream data size/length in advance as we are reading data via network. Most of the other examples available might be using an array, but that might lead to either wastage of some space or there will be space scarcity to read all the data and store the data into the array as the size might be more or lesser than the required space. I am storing the length of the data which we read in a variable request_len .

I am using a mutable temporary Vector variable buffer and try reading the 512 bytes inside a loop, then we are using a match pattern while reading the data to know the number of bytes of data which were read. Depending on the number of bytes read from TcpStream, which is n here, the corresponding code placed in the arm of the match block will be executed. If n is 0, i.e there is no data and nothing was read, we just need to break out of the loop and stop reading the stream. Otherwise, we just add the number of bytes read to the variable request_len . If n is lesser than the buffer size (512 here), we understand that the Stream has lesser data than our buffer size, we add the data how much ever it was there , by adding the mut buffer[..n] to the mutable vector request_buffer and then we break out of the loop as we have no more data under the current iteration of the loop. If n is equal to our buffer size ( 512 here), we read the data and add the data into mutable vector request_buffer . In this case, we don’t break out of the loop and try reading more data out of the TcpStream if available .

I hope this post will be useful to you all who are learning Rust socket / TcpStream programming . The same concept can be used for reading data from socket in other languages too. Thanks for reading the post. Please post your questions and ideas in comments. Feel free to reach out to me if you have better ways of doing this or for any questions. Follow me on Twitter for more updates and if you want to connect with me.

Rust Development Environment Setup

In this post, I am going to share how to set up a system for Rust development. This tutorial can be used either on Windows OS or on Linux OS.

Steps

  1. Install rustup which will install the rustc , cargo and other things required for Rust from its official website ( https://www.rust-lang.org/tools/install ) .
  2. Configure the PATH variable of your system so that you can invoke rustc , cargo and other rust related commands. Verify it by invoking these commands in terminal.
  3. The successful installation of Rust can also be verified by invoking the command : rustc --version
  4. If you are a Windows OS user, please install the  Visual Studio C++ Build tools . You can also read my previous post regarding this, if you want to know the setup steps in details .
  5. The next step is to verify that we are able to compile a HelloWorld program. To do that we can either manually write a Hello World program or use cargo to generate it. I will be using cargo to make this simple. To do that, use the command : cargo new hello
  6. Navigate to the newly created directory ( hello in this case), and try compiling and running the program : cargo build && cargo run
Compiling and running a simple Rust program

7. Now, we need to setup a Text Editor for Rust development or we can use IDE. I prefer using Text Editor and I am using VSCode (Visual Studio Code) now a days. So, I will be setting up VSCode for Rust development such as syntax highlighting, auto completion, etc.

8. Open VSCode and click on Extensions and install the Rust Extension .

9. Restart the VSCode and start working with Rust code and projects and we will see the features of auto completion, syntax highlighting, etc.

VSCode Rust Extension screenshot

10. Enjoy Rust programming and keep on learning Rust now 🙂

I hope this tutorial will be useful to you all. Let me know if you have any questions regarding this tutorial or if you want to ask me anything about Rust. You can also reach out to me through my Twitter account.

Install Visual Studio for C , C++ and Rust Development on Windows OS

In this post, we are going to setup C/C++ development environment by using Visual Studio on Windows OS. This post will also help you all to setup Rust development environment on Windows which I will share later.

Tools Required :

  1. Install the latest appropriate Visual Studio 2019 Installer.
  2. Install Visual Studio Code ( lightweight editor which we can use for writing C/C++ & other languages code)

Steps :

  1. Launch Visual Studio Installer & it will launch a dialog showing the Build Tool Workloads. Check the Desktop development with C++ workload (as shown in screenshot below) and then click on Install . I have also installed C++ Clang tools for Windows.

2. It might take a while to install all the selected tools depending your internet speed and your system. You might have to restart your system for the complete setup.

3. Click on Windows Start Menu & then type Developer and you should see the following screen ( as shown below). Click on Developer Command Prompt for VS 2019 ( depending upon your version) and launch it.

4. After launching the Developer Command Prompt for VS 2019 , we can test the installation of Microsoft Optimizing C/C++ Compiler , cl.exe by running the command cl (as shown in screenshot)

5. If everything is installed properly, then the cl command will show you the Microsoft C/C++ compiler message & version.

6. We have to use cl command ( cl.exe ) to compile & build C/C++ files which I will share in next tutorial. We will use lightweight text editor Visual Studio Code for the next tutorial ( it is different from Visual Studio IDE ).

Note : Rust compiler needs Visual Studio C/C++ Build Tools linker to compile the files on Windows OS.

I hope this post will be useful to you all who wants to setup C/C++ and Rust development environment on Windows OS.

References :

  1. https://code.visualstudio.com/docs/cpp/config-msvc
  2. https://www.40tude.fr/how-to-compile-cpp-code-with-vscode-cl/

How to get Facebook Note/Post comments by using Facebook API

In this post, I am sharing how  we can get all the comments of a Facebook Post/Note by using Facebook API.

Recently, I tried to retrieve comments on my Facebook Notes by using Facebook Note API, but I found that Note API had been depreciated and could not be used.

fb1

I thought that I won’t be able to get comments on my Facebook Notes . But, I finally found a way to do so after playing with API for some days.

Many users may be trying to get all the comments on their Facebook Notes as Notes may contain many important links, tutorials,etc. This method can also be used for getting comments of Facebook Posts also.

Facebook Notes can be considered similar to that of Facebook  Posts. To get comments of any facebook Note/Post, we need its unique post-id whose prefix part is always profile-id_ and last part is numerical part of Note URL.

You need to visit https://developers.facebook.com/tools/explorer/ and get your Graph API Access Token for using Facebook Graph API Explorer .Just selelct all those permission which you want to use.

Getting Facebook Profile Name & ID:

fb2

Selecting any Facebook Note/Post and getting its last Numerical part of URL:

Screenshot from 2018-04-10 17-00-38.png

Getting Facebook Note/Post post-id

Now, we can easily form this Note post-id by adding profile-id and last numerical part of URL as shown in screenshot( profile-id +underscore + last numerical part of URL).

fb4

By using the above method we can easily get Facebook Note ID .But, we have to do things manually each time for different posts/notes each time we want to retrieve comments. So, this method will inefficient.Thus, we should use different method as described below.

Tools Required:

1. python 3

2.  facebook-sdk (python module)

you can easily install facebook-sdk by using pip as shown below:

pip install facebook-sdk

3.  FBNotes

Download the above file and Extract it. Change your working directory to the directory where you extracted the files.

Edit fb_notes.py with your access token & other options as described below , then run the python script as shown below.

python fb_notes.py

Screenshot from 2018-04-10 16-26-57.png

Using facebook-sdk

If you see the second screenshot, you can see that I had created my Facebook Note on 10 February  2017. I have used that date in my code to get posts created on that day .Using this approach, we can limit time-period to get posts and their post-id. Thus, this approach makes work easy.

You should use your own Facebook Note/Post date on which you created it.

1. Getting Facebook Profile Name & ID :

import facebook
token = "YOUR_ACCESS_TOKEN"
account_data = graph.get_object("me")
print("Name:", account_data["name"])
print("Profile ID: ", account_data["id"])

2. Selecting Facebook Note/Post & Getting its post-id

posts = graph.get_object("me/feed?since=10 February 2017 & until=11 February 2017")
note_data = posts["data"][0]
print("Post/Note Title: ",note_data["message"])
note_postid = note_data["id"]
print("Post/ Note ID: ", note_postid)

3. Getting Comments & total number of comments

# get comment data . Not all comments will be returned by facebook API
comments_data = graph.get_object(note_postid + "/comments")
# get total number of comments
comments_data = graph.get_object(note_postid + "?fields=comments.summary(true)")
comments_count = comments_data["comments"]["summary"]["total_count"]
print("Post/Note Comments count: ", comments_count) 

4. Getting total comments on Facebook Note/Post

comments_data = graph.get_object(note_postid + "/comments?limit=" + str(comments_count))
cc = 0
print("No.","\t", "Comment")
for comment in comments_data["data"]:
 print(cc," ", comment["message"])
 cc += 1

Complete Code

Screenshot from 2018-04-10 18-32-17

Now,edit your access token & other things as described above  depending upon your requirements, then run the python script as shown below.

python  fb_notes.py

Output :

Screenshot from 2018-04-10 16-29-14.png

We can also save the comments in a file for later use.By using the above methods , we can get Facebook Notes/Posts comments and other data.

I hope this post will be useful for them who want to use Facebook API & its python SDK.

If you have any questions or you face any problem, please post them in comments.

Thanks for reading the post. Share it with others, if you like it.

How to set up Apache2 Server for PERL CGI & PHP programming with MySQL Server support on Linux/Ubuntu OS

Hello,everyone.Today,I want to share how we can set up Apache2  Server for PERL CGI and  PHP programming along with MySQL Server support on Linux/Ubuntu OS.

I am setting up Apache2 Server on Ubuntu 16.04.You can do the same on your system easily by following my steps.

Steps:

1.Install Apache2:
sudo apt install apache2

2.To start Apache2 server and test it (shown in screenshot):
sudo systemctl start apache2

To check status:
sudo systemctl status apache2

(Note: If you get any error in starting Apache2 then nginx  or other server maybe running on system, so you can stop nginx by using this command: sudo systemctl stop nginx ) and rerun the same command to start apache2.On my system, nginx starts automatically on reboot, so I have to stop it,otherwise apache2 server won’t start.

Screenshot from 2017-11-12 00-23-48.png

if you see output as “active (running)”,then apache2 server is running successfully.Now,if you access  http://localhost/  in your browser, then you will see Apache2 Default Page.

[Optional]
To stop Apache2 server:
sudo systemctl stop apache2
To restart Apache2 server:
sudo systemctl restart apache2

3.Install Perl if it is not installed.
sudo apt install perl

4.To enable CGI for Apache2:
sudo a2enmod cgi
sudo systemctl restart apache2

5. To write CGI files in /var/www/cgi-bin/ ,you need to use this command otherwise Apache2 will read CGI files from /usr/lib/cgi-bin/  :

sudo vi /etc/apache2/sites-available/000-default.conf

This will open vi editor and lines will begin like this and we need to add the 3rd line given below(shown in screenshot) , and then save the file:

ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# Add this 3rd line without editing other lines(you can ignore my other extra  lines  or use them if you want)
ScriptAlias /cgi-bin/ /var/www/cgi-bin/

Screenshot from 2017-11-12 00-59-54

6.Install MySQL if it is not installed (Remember MySQL password while installing as we need to use it later):
sudo apt-get install mysql-server

7.To run PERL programs which uses MySQL, you may need to install DBI & DBD:mysql for PERL by using these commands:
sudo cpan

Now cpan prompt will appear.Type these on prompt:
cpan>install DBI
capn>install DBD:mysql

Screenshot from 2017-11-06 16-59-12

8.To start MySQL server:
sudo systemctl start mysql
To check status of MySQL server:
sudo systemctl status mysql

Screenshot from 2017-11-12 00-40-22.png

if you see the output as “active (running)” , then MySQL server is running successfully.

9.To use PHP with Apache2:
sudo apt install php libapache2-mod-php
Screenshot from 2017-11-06 20-29-54

10.To enable PHP for apache2( change php7.0 with your version or just try ‘php’) :
sudo a2enmod php7.0

sudo systemctl restart apache2

# For PHP7.0
sudo apt install php7.0-mbstring

Screenshot from 2017-11-06 20-30-00

11.To enable PHP to connect with MySQL, use this command:
sudo apt install php-mysql

12.All the steps are complete now if all the previous steps are completed successfully .You need to place PERL CGI files in /var/www/cgi-bin/ directory so that you can access them in browser with URL http://localhost/cgi-bin/cgi.pl    .You need to write HTML and PHP files in /var/www/html directory so that you can acesss them in browser with URL http://localhost/index.html

Now, Apache2  Server  is set up successfully for PERL CGI and PHP programming along with MySQL support on the system

Thanks for reading the post.I hope this post has been helpful and easy to understand.If you have any question or you face any error,please post it in comments.

How to run and manage different versions of Python with virtual environment support by using pyenv

In this post,I am sharing how we can run different versions of python easily with virtual environment support  by usng pyenv .I am using pyenv these days.I find it better than using virtualenv .My currently activated environment remains activated even after restarting Terminal shell which I prefer.Another feature of pyenv  is that you can set environment local to any folder.

Thanks : Yamashita  (Author of pyenv )

Steps :

1.Use pyenv-installer   to install pyenv.You can install pyenv by using this command on Terminal :

$ curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash

2.To update  pyenv ,use this command :

$ pyenv update

Screenshot from 2017-07-29 11-25-48.png

3.Open your .bashrc  file and make sure that these lines are added to it .Otherwise,you need to add these lines  to your .bashrc  file  by editing the file wih sudo command:

# Load pyenv automatically by adding
# the following to ~/.bash_profile:

export PATH=”/home/gaurav/.pyenv/bin:$PATH”
eval “$(pyenv init -)”
eval “$(pyenv virtualenv-init -)”

4. To install specific version of Python ,say Python 3.6.1 ,use this command :

$ pyenv install 3.6.1

5.To create a virtual environment system ,say  test which uses Python  3.6.1 which we installed in previous step,you can use this command :

$ pyenv virtualenv 3.6.1 test

6.To activate this new virtual environment test ,you need to use this command :

$ pyenv virtualenv 3.6.1 test

7.To list all virtual environments of pyenv ,use this command :

$ pyenv versions

8.To switch back to system Python ,use this command :

$ pyenv global system

Screenshot from 2017-07-29 11-29-28.png

9.To uninstall any virtual environment ,say test ,use this command and Enterey  when it asks for confirmation :

$ pyenv uninstall test

Now,you can easily run different versions of Python along with virtual environment support.

Thanks  for reading my post.I hope this post will be useful for them who  want to manage different versions of python with virtual environment support .If you have any query/question,please post in comments section.

How to decompile compiled .pyc python files to find/see original source code

Hello,everyone.In this post,i am sharing how to decompile compiled python files which are in .pyc formats usually.It may be useful for reverse enginering and if you want to know the original source code of any compiled python files.It may be also useful whenever  your original .py  python file is deleted unknowingly and there is only compiled .pyc file left  on disk and you want your original .py file back.In all those cases, this method can be used.

I have used Ubuntu OS here and it can be used on Windows OS also.

Tools Required :

uncompyle6  : https://github.com/rocky/python-uncompyle6/

Thanks :R. Bernstein (Author of uncompyle6)

Steps :

1.Install uncompyle6 by using pip on Terminal or you can download from above link and install it by running its setup.py file.To install uncompyle6 by using pip,use this command on Terminal :

pip install uncompyle6

 

2.After installation of  uncompyle6 ,you can check its successfull installation and its usage by running uncompyle6 command on Terminal (see screenshot).

 

3.To decompile any file in current diectory ,use command (see screenshot for example): uncompyle6 -o . <file-name.pc> 

Example : uncompyl6 -o . txfile.pyc rxfile.pyc

Screenshot from 2017-07-01 13-38-05

 

4.You will see your decompiled files created with same name in the current working directory(or desired directory) .Now,you can open this decompiled file with any Text Editor and see original source code.

Screenshot from 2017-07-01 13-38-46.png

 

5.if you want to see decompiled code on terminal(standard output),use command(see screenshot for example ): uncompyle6 <filename.pyc>

Screenshot from 2017-07-01 13-39-59.png

 

Thanks for reading my post.I hope this will be useful for python users who want to decompile compiled python files.

 

 

 

 

How to fix Realtek RTL8723BE Wireless Network Adapter Low Wi-Fi Signal Issue on Ubuntu/Linux OS

Hello,everyone.Today , I  want to share how to fix Realtek RTL8723BE Wireless Network Adapter Low Wi-Fi Signal Issue on Ubuntu/Linux OS.This tutorial can be also used for other Realtek Wireless Network Adapters supported by rtlwifi_new .

I have a great interest in using Using Ubuntu OS , so I installed latest version of Ubuntu OS alongside Windows OS.But, I faced low Wi-Fi signal issue on Ubuntu OS .Ubuntu OS failed to find many Wi-Fi networks which I could easily find & use on Windows OS.  Then,I started finding solutions to my problem and I found  a working solution.

Tools Required :

rtlwifi_new : https://github.com/lwfinger/rtlwifi_new

Steps :

1.Download rtlwifi_new from above link and extract it to Desktop (or to your desitrd folder).

2.Open Terminal and change your directory to the folder where you extracted rtlwifi_new zip file (here , Desktop/rtlwifi_new-master )  by using cd  command .See Screenshot given below :

cd   Desktop/rtlwifi_new-master 

3.Now,run this command in Terminal as shown in Screenshot given below:

make clean  (optional for first time installation,you can use it for further installation)

make 

Screenshot from 2017-06-18 12-17-22.png

 

4.After that ,run this command in terminal  as shown in screenshot given below:

sudo make install  

Screenshot from 2017-06-18 12-19-13.png

 

5.If everything is allright,you will see the message  ” Install rtlwifi SUCCESS  “  . It means that rtlwifi has beeen installed successfully.

6.Now,run this command as shown in screenshot given below :

sudo modprobe rtl8723be 

7.After that , run this command as shown in screenshot given below :

echo “options rtl8723be ant_sel=2” | sudo tee /etc/modprobe.d/rtl8723be.conf

8.This step is optional.If you want to see that  text contents are written successfully to /etc/modprobe.d/rtl8723be.conf .you can use this command  as shown in screenshot given below :

cat /etc/modprobe.d/rtl8723be.conf

Screenshot from 2017-06-18 12-27-53.png

 

9.If all the above commands ae executed successfully,then everything has been done. Now,you need to restart your computer and you will see Wi-Fi working properly and your computer will find available Wi-Fi   networks in your area.

10.After restarting  your computer, select Wi-Fi network which you want to connect .

Screenshot from 2017-06-18 12-35-14.png

 

I hope this post will be useful for many users who use Realtek Wireless Network Adapter  and face low Wi-Fi signal issues on Ubuntu OS.

If you have any query or you face any problem ,please comment.Thank you for reading my post.

Thanks : lwfinger ( Author of rtlwifi_new)

Sources:

1.  https://askubuntu.com/questions/645220/unable-to-connect-wifi-ubuntu-14-04-lts-hp-pavilion-network-driver-rtl8723be/729660#729660  

2. https://askubuntu.com/questions/635625/how-do-i-get-a-realtek-rtl8723be-wireless-card-to-work/635629#635629

3. https://connectwww.com/how-to-solve-realtek-rtl8723be-weak-wifi-signal-problem-in-ubuntu/4625/

 

 

 

Using Python3 and Python2 on Windows OS with pip support

Hello everyone.Today,I am going to share how to use Python3 and Python2 with pip support  on Windows OS.If you try to install latest Python version 3.6 ,it provides you the option of adding Python 3.6 to PATH ,but this is not provided by Python2 installer still.Many users may find it difficult to use both version with corresponding pip on Windows OS.

So,I am sharing this method which helped me to use Python2 and Python3 simultaneously.

STEPS :

1.Download Python3 and Python2 installer from python.org .

2.Run Python3 installer and tick(enable) “Add Python 3.6 to Path” as shown in screenshot so that you can run Python3 by python command on Terminal/Shell.

p3s

 

3.You can run Python3 by using python command and its pip by using pip command.

4.Run Python2 installer and install Python2 .

5.Now ,you need to edit system environment  variable PATH as shown in screenshot below  for using Python2  and its pip2 in Terminal/shell :

path_setup

 

6.Click on Edit Button .After that all the enteries of  PATH  variable will be displayed.Now,click on New Button and add this entry as shown in screenshot:

C:\Python27\Scripts

path_edit.JPG

 

7.Click on OK button to save and make it sure that the entry added to PATH varaiable is not C:\Python27\   . Otherwise , python command will run Python2 instead of Python3 .

8. Again add a new entery PY_PATH to system variables and set its value to 2 if you want to run python2 by using py command.

9.Now, you can use Python 3 by using python or py -3 . You can use pip for python 3 by pip or pip3 command .You can use Python2 by using py command or py-2 command .You can use pip for Python2 by using pip2 command.(See Screenshot)

pipnnn.JPG

 

If every step is followed correctly,you will see Python3 and Python2 running successfully with pip support in Terminal.

If you have any query or you need help,post in comments.I will be glad to help you.

Thanks for reading my post.I hope my post will be useful to Python users who are using Windows OS.

 

 

 

Bitly v1.00.0 pys60 app for Symbian S60 by gauravssnl based on bitly_python API

Bitly v1.00.0 pys60 app by gauravssnl based on bitly python API

Geneate bit.ly short URL of any long URL easily and exapand bit.ly URL to get original link.

Bit.ly URLs are used for sharing links on social networking sites and on blogs to make long URLs shorter.

Download link : Bitly app v1.00.0 by gauravssnl.zip

Screenshot :

ss

 

Features :

-Generate bit.ly link

-Expand bit.ly link

Steps :

1. Register an account on bitly.com by visiting this link : https://bitly.com/a/sign_up

2.After that ,you need to get your bitly Access Token of your account

3.Now open Bitly app , and enter your Access Token in Settings from menu.

4.Now,click on Connect .If your Access Token is correct, you will be successfully logged in and your users details will be displayed. If this does not occur, check your Access Token and try again.

5.Now,you can generate bit.ly short URLs and expand bit.ly URLS to get original links

Thanks : Jehiah Czebotar (bitly_ api author)

Thanks everyone.