C language decompression of huawei firmware instance code

  • 2020-04-02 01:27:47
  • OfStack



#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXLEN 10240
void usage();
int main(int argc,char *argv[])
{
    int count,packetLength,dataLength,olddataLength,datasum,line,remainder,*Length;
    char *FILENAME,*OUTNAME;
    char int2char[10];
    unsigned char buffer[MAXLEN];
    FILE *INFILE,*OUTFILE;

    //Gets the parameters of the input
    if(argc == 1)
        FILENAME="UPDATE.APP";
    else
        FILENAME=argv[1];

    //Open the input file in binary
    if((INFILE = fopen(FILENAME, "rb")) == NULL) usage();

    //Create a folder and go into the directory
    mkdir("output");
    chdir("output");

    //Skip 92 null bytes
    fseek(INFILE, 92, 0);

    for(count=1;INFILE != NULL;count++)
    {
        //Determine whether it is an index header for huawei firmware
        fread(buffer, 4, 1, INFILE);
        if(buffer[0] != 0x55) break;
        if(buffer[1] != 0XAA) break;
        if(buffer[2] != 0x5A) break;
        if(buffer[3] != 0xA5) break;

        //Gets the header file length
        fread(buffer, 4, 1, INFILE);
        Length = (int *)buffer;
        packetLength=*Length;

        //Skip 16 bytes
        fseek(INFILE, 16, 1);

        //Get content length
        fread(buffer, 4, 1, INFILE);
        Length = (int *) buffer;
        dataLength=*Length;

        //Concatenate integers and strings and copy them to file names
        itoa(count, int2char, 10);
        OUTNAME=strcat(int2char, ".img");

        //Skip to the end of the header file
        fseek(INFILE, packetLength-28, 1);

        //Create a file
        if((OUTFILE = fopen(OUTNAME, "wb")) == NULL)
        {
            printf("Unrecognised file format. Wrong identifier.n");
            return -1;
        } else printf("Extracted output/%sn",OUTNAME);

        //Divide the content data into sections
        datasum=dataLength/MAXLEN;

        for(line=0;line <= datasum;line++)
        {
            //Getting content data
            if(datasum == line)
                fread(buffer, dataLength % MAXLEN, 1, INFILE);
            else
            fread(buffer, MAXLEN, 1, INFILE);

            //The output file
            if(datasum == line)
                fwrite(buffer, dataLength % MAXLEN, 1, OUTFILE);
            else
            fwrite(buffer, MAXLEN, 1, OUTFILE);
        }

        // Shut down The output file
        fclose(OUTFILE);

        //The pointer is rounded, a multiple of 4
        remainder = 4 - (ftell(INFILE) % 4);
        if (remainder < 4)
        {
            //Fill the remaining bytes
            fseek(INFILE, remainder, 1);
        }
    }
    //Close the input file
    fclose(INFILE);
    return 0;
}
void usage()
{
    //Help function
    printf("uasge: unpack_update.exe [UPDATE.APP|UPDATA.APP]n");
    exit(0);
}


Related articles: