文档章节

PHP解析Android APK包的XML文件

tfc
 tfc
发布于 2013/03/27 15:50
字数 2007
阅读 1.4K
收藏 2


2012.07.05更新: 某些系统apk文件的字符串表不是使用双字节,会导致解码越界. 修改了getStringTab()成员函数, 详细请看代码部分.

最近做的一个项目需要用PHP直接读取apk包中的信息,如:包名,入口地址,版本号等信息。这些信息都保存在apk包中的AndroidManifest.xml文件中。但是在编译apk包的过程中,所有XML文件都经过了压缩编码,直接读取xml文件内容是无法解析出需要的信息的。

Google搜索了一下没有找到这个功能的PHP实现,只有找到一个Java工具AXMLPrinter,可以还原经过压缩后的XML文件内容。于是就参考了这个Java工具的源码,按照这个压缩后的XML文件格式写了一个PHP的还原功能类。

类实现了直接读取apk包中指定的XML文件内容(使用PHP的zip功能函数直接解压apk包),无需手动解压apk获取文件。

类功能不多,所有供外部调用的方法都表明了公开,私有函数均是解码函数,不推荐直接调用。

使用例子:

?
1
2
3
4
5
6
<?php
require('apk_parser.php');
$p=newApkParser();
$res=$p->open('android_app.apk');
echo$p->getXML();
?>

apk_parser.php源代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
<?php
/******************************************************
 * Android APK File Parser
 * Author: Katana
 * Version: v0.1
 * Web: http://www.win-ing.cn
 *
 * 功能:解析安卓apk包中的压缩XML文件,还原和读取XML内容
 *
 * 依赖功能:需要PHP的ZIP包函数支持。
 ******************************************************/
 
classApkParser{
//----------------------
// 公共函数,供外部调用
//----------------------
    publicfunctionopen($apk_file,$xml_file='AndroidManifest.xml'){
        $zip=newZipArchive;
        if($zip->open($apk_file) === TRUE) {
            $xml=$zip->getFromName($xml_file);
            $zip->close();
            if($xml){
                try{
                    return$this->parseString($xml);
                }catch(Exception$e){
                }
            }
        }
        returnfalse;
    }
 
    publicfunctionparseString($xml){
        $this->xml =$xml;
        $this->length =strlen($xml);
 
        $this->root =$this->parseBlock(self::AXML_FILE);
        returntrue;
    }
 
    publicfunctiongetXML($node=NULL,$lv=-1){
        if($lv== -1)$node=$this->root;
        if(!$node)return'';
 
        if($node['type'] == self::END_TAG)$lv--;
        $xml= ($node['line'] == 0 ||$node['line'] ==$this->line) ?'':"\n".str_repeat('  ',$lv);
        $xml.=$node['tag'];
        $this->line =$node['line'];
        foreach($node['child']as$c){
            $xml.=$this->getXML($c,$lv+1);
        }
        return$xml;
    }
 
    publicfunctiongetPackage(){
        return$this->getAttribute('manifest','package');
    }
 
    publicfunctiongetVersionName(){
        return$this->getAttribute('manifest','android:versionName');
    }
 
    publicfunctiongetVersionCode(){
        return$this->getAttribute('manifest','android:versionCode');
    }
 
    publicfunctiongetAppName(){
        return$this->getAttribute('manifest/application','android:name');
    }
 
    publicfunctiongetMainActivity(){
        for($id=0; true;$id++){
            $act=$this->getAttribute("manifest/application/activity[{$id}]/intent-filter/action",'android:name');
            if(!$act)break;
            if($act=='android.intent.action.MAIN')return$this->getActivity($id);
        }
        returnNULL;
    }
 
    publicfunctiongetActivity($idx=0){
        $idx=intval($idx);
        return$this->getAttribute("manifest/application/activity[{$idx}]",'android:name');
    }
 
    publicfunctiongetAttribute($path,$name){
        $r=$this->getElement($path);
        if(is_null($r))returnNULL;
 
        if(isset($r['attrs'])){
            foreach($r['attrs']as$a){
                if($a['ns_name'] ==$name)return$this->getAttributeValue($a);
            }
        }
        returnNULL;
    }
 
//----------------------
// 类型常量定义
//----------------------
    constAXML_FILE             = 0x00080003;
    constSTRING_BLOCK          = 0x001C0001;
    constRESOURCEIDS           = 0x00080180;
    constSTART_NAMESPACE       = 0x00100100;
    constEND_NAMESPACE         = 0x00100101;
    constSTART_TAG             = 0x00100102;
    constEND_TAG               = 0x00100103;
    constTEXT                  = 0x00100104;
 
    constTYPE_NULL             =0;
    constTYPE_REFERENCE        =1;
    constTYPE_ATTRIBUTE        =2;
    constTYPE_STRING           =3;
    constTYPE_FLOAT            =4;
    constTYPE_DIMENSION        =5;
    constTYPE_FRACTION         =6;
    constTYPE_INT_DEC          =16;
    constTYPE_INT_HEX          =17;
    constTYPE_INT_BOOLEAN      =18;
    constTYPE_INT_COLOR_ARGB8  =28;
    constTYPE_INT_COLOR_RGB8   =29;
    constTYPE_INT_COLOR_ARGB4  =30;
    constTYPE_INT_COLOR_RGB4   =31;
 
    constUNIT_MASK             = 15;
    privatestatic$RADIX_MULTS=array(0.00390625, 3.051758E-005, 1.192093E-007, 4.656613E-010);
    privatestatic$DIMENSION_UNITS=array("px","dip","sp","pt","in","mm","","");
    privatestatic$FRACTION_UNITS =array("%","%p","","","","","","");
 
    private$xml='';
    private$length= 0;
    private$stringCount= 0;
    private$styleCount = 0;
    private$stringTab=array();
    private$styleTab =array();
    private$resourceIDs=array();
    private$ns=array();
    private$cur_ns= NULL;
    private$root= NULL;
    private$line= 0;
 
//----------------------
// 内部私有函数
//----------------------
    privatefunctiongetElement($path){
        if(!$this->root)returnNULL;
        $ps=explode('/',$path);
        $r =$this->root;
        foreach($psas$v){
            if(preg_match('/([^\[]+)\[([0-9]+)\]$/',$v,$ms)){
                $v=$ms[1];
                $off=$ms[2];
            }else{
                $off= 0;
            }
            foreach($r['child']as$c){
                if($c['type'] == self::START_TAG &&$c['ns_name'] ==$v){
                    if($off== 0){
                        $r=$c;continue2;
                    }else{
                        $off--;
                    }
                }
            }
            // 没有找到节点
            returnNULL;
        }
        return$r;
    }
 
    privatefunctionparseBlock($need= 0){
        $o= 0;
        $type=$this->get32($o);
        if($need&&$type!=$need)thrownewException('Block Type Error', 1);
        $size=$this->get32($o);
        if($size< 8 ||$size>$this->length)thrownewException('Block Size Error', 2);
        $left=$this->length -$size;
 
        $props= false;
        switch($type){
            caseself::AXML_FILE:
                $props=array(
                    'line'=> 0,
                    'tag'=>'<?xml version="1.0" encoding="utf-8"?>'
                );
            break;
            caseself::STRING_BLOCK:
                $this->stringCount =$this->get32($o);
                $this->styleCount  =$this->get32($o);
                $o+= 4;
                $strOffset=$this->get32($o);
                $styOffset=$this->get32($o);
                $strListOffset=$this->get32array($o,$this->stringCount);
                $styListOffset=$this->get32array($o,$this->styleCount);
                $this->stringTab =$this->stringCount > 0 ?$this->getStringTab($strOffset,$strListOffset) :array();
                $this->styleTab  =$this->styleCount > 0 ?$this->getStringTab($styOffset,$styListOffset) :array();
                $o=$size;
            break;
            caseself::RESOURCEIDS:
                $count=$size/ 4 - 2;
                $this->resourceIDs =$this->get32array($o,$count);
            break;
            caseself::START_NAMESPACE:
                $o+= 8;
                $prefix=$this->get32($o);
                $uri=$this->get32($o);
 
                if(empty($this->cur_ns)){
                    $this->cur_ns =array();
                    $this->ns[] = &$this->cur_ns;
                }
                $this->cur_ns[$uri] =$prefix;
            break;
            caseself::END_NAMESPACE:
                $o+= 8;
                $prefix=$this->get32($o);
                $uri=$this->get32($o);
 
                if(empty($this->cur_ns))break;
                unset($this->cur_ns[$uri]);
            break;
            caseself::START_TAG:
                $line=$this->get32($o);
 
                $o+= 4;
                $attrs=array();
                $props=array(
                    'line'=>$line,
                    'ns'=>$this->getNameSpace($this->get32($o)),
                    'name'=>$this->getString($this->get32($o)),
                    'flag'=>$this->get32($o),
                    'count'=>$this->get16($o),
                    'id'=>$this->get16($o)-1,
                    'class'=>$this->get16($o)-1,
                    'style'=>$this->get16($o)-1,
                    'attrs'=> &$attrs
                );
                $props['ns_name'] =$props['ns'].$props['name'];
                for($i=0;$i<$props['count'];$i++){
                    $a=array(
                        'ns'=>$this->getNameSpace($this->get32($o)),
                        'name'=>$this->getString($this->get32($o)),
                        'val_str'=>$this->get32($o),
                        'val_type'=>$this->get32($o),
                        'val_data'=>$this->get32($o)
                    );
                    $a['ns_name'] =$a['ns'].$a['name'];
                    $a['val_type'] >>= 24;
                    $attrs[] =$a;
                }
                // 处理TAG字符串
                $tag="<{$props['ns_name']}";
                foreach($this->cur_nsas$uri=>$prefix){
                    $uri=$this->getString($uri);
                    $prefix=$this->getString($prefix);
                    $tag.=" xmlns:{$prefix}=\"{$uri}\"";
                }
                foreach($props['attrs']as$a){
                    $tag.=" {$a['ns_name']}=\"".
                            $this->getAttributeValue($a).
                            '"';
                }
                $tag.='>';
                $props['tag'] =$tag;
 
                unset($this->cur_ns);
                $this->cur_ns =array();
                $this->ns[] = &$this->cur_ns;
                $left= -1;
            break;
            caseself::END_TAG:
                $line=$this->get32($o);
                $o+= 4;
                $props=array(
                    'line'=>$line,
                    'ns'=>$this->getNameSpace($this->get32($o)),
                    'name'=>$this->getString($this->get32($o))
                );
                $props['ns_name'] =$props['ns'].$props['name'];
                $props['tag'] ="</{$props['ns_name']}>";
                if(count($this->ns) > 1){
                    array_pop($this->ns);
                    unset($this->cur_ns);
                    $this->cur_ns =array_pop($this->ns);
                    $this->ns[] = &$this->cur_ns;
                }
            break;
            caseself::TEXT:
                $o+= 8;
                $props=array(
                    'tag'=>$this->getString($this->get32($o))
                );
                $o+= 8;
            break;
            default:
                thrownewException('Block Type Error', 3);
            break;
        }
 
        $this->skip($o);
        $child=array();
        while($this->length >$left){
            $c=$this->parseBlock();
            if($props&&$c)$child[] =$c;
            if($left== -1 &&$c['type'] == self::END_TAG){
                $left=$this->length;
                break;
            }
        }
        if($this->length !=$left)thrownewException('Block Overflow Error', 4);
        if($props){
            $props['type'] =$type;
            $props['size'] =$size;
            $props['child'] =$child;
            return$props;
        }else{
            returnfalse;
        }
    }
 
    privatefunctiongetAttributeValue($a){
        $type= &$a['val_type'];
        $data= &$a['val_data'];
        switch($type){
            caseself::TYPE_STRING:
                return$this->getString($a['val_str']);
            caseself::TYPE_ATTRIBUTE:
                returnsprintf('?%s%08X', self::_getPackage($data),$data);
            caseself::TYPE_REFERENCE:
                returnsprintf('@%s%08X', self::_getPackage($data),$data);
            caseself::TYPE_INT_HEX:
                returnsprintf('0x%08X',$data);
            caseself::TYPE_INT_BOOLEAN:
                return($data!= 0 ?'true':'false');
            caseself::TYPE_INT_COLOR_ARGB8:
            caseself::TYPE_INT_COLOR_RGB8:
            caseself::TYPE_INT_COLOR_ARGB4:
            caseself::TYPE_INT_COLOR_RGB4:
                returnsprintf('#%08X',$data);
            caseself::TYPE_DIMENSION:
                return$this->_complexToFloat($data).self::$DIMENSION_UNITS[$data& self::UNIT_MASK];
            caseself::TYPE_FRACTION:
                return$this->_complexToFloat($data).self::$FRACTION_UNITS[$data& self::UNIT_MASK];
            caseself::TYPE_FLOAT:
                return$this->_int2float($data);
        }
        if($type>=self::TYPE_INT_DEC &&$type< self::TYPE_INT_COLOR_ARGB8){
            return(string)$data;
        }
        returnsprintf('<0x%X, type 0x%02X>',$data,$type);
    }
 
    privatefunction_complexToFloat($data){
        return(float)($data& 0xFFFFFF00) * self::$RADIX_MULTS[($data>>4) & 3];
    }
    privatefunction_int2float($v) {
        $x= ($v& ((1 << 23) - 1)) + (1 << 23) * ($v>> 31 | 1);
        $exp= ($v>> 23 & 0xFF) - 127;
        return$x* pow(2,$exp- 23);
    }
    privatestaticfunction_getPackage($data){
        return($data>> 24 == 1) ?'android:':'';
    }
 
    privatefunctiongetStringTab($base,$list){
        $tab=array();
        foreach($listas$off){
            $off+=$base;
            $len=$this->get16($off);
            $mask= ($len>> 0x8) & 0xFF;
            $len=$len& 0xFF;
            if($len==$mask){
                if($off+$len>$this->length)thrownewException('String Table Overflow', 11);
                $tab[] =substr($this->xml,$off,$len);
            }else{
                if($off+$len* 2 >$this->length)thrownewException('String Table Overflow', 11);
                $str=substr($this->xml,$off,$len* 2);
                $tab[] = mb_convert_encoding($str,'UTF-8','UCS-2LE');
            }
        }
        return$tab;
    }
    privatefunctiongetString($id){
        if($id> -1 &&$id<$this->stringCount){
            return$this->stringTab[$id];
        }else{
            return'';
        }
    }
    privatefunctiongetNameSpace($uri){
        for($i=count($this->ns);$i> 0; ){
            $ns=$this->ns[--$i];
            if(isset($ns[$uri])){
                $ns=$this->getString($ns[$uri]);
                if(!empty($ns))$ns.=':';
                return$ns;
            }
        }
        return'';
    }
    privatefunctionget32(&$off){
        $int= unpack('V',substr($this->xml,$off, 4));
        $off+= 4;
        returnarray_shift($int);
    }
    privatefunctionget32array(&$off,$size){
        if($size<= 0)returnNULL;
        $arr= unpack('V*',substr($this->xml,$off, 4 *$size));
        if(count($arr) !=$size)thrownewException('Array Size Error', 10);
        $off+= 4 *$size;
        return$arr;
    }
    privatefunctionget16(&$off){
        $int= unpack('v',substr($this->xml,$off, 2));
        $off+= 2;
        returnarray_shift($int);
    }
    privatefunctionskip($size){
        $this->xml =substr($this->xml,$size);
        $this->length -=$size;
    }
}
?>
此条目由  绒毛 发表在  AndroidPHP 分类目录,并贴了  apkPHPxml 标签。将 固定链接加入收藏夹。

本文转载自:http://blog.win-ing.cn/archives/69

tfc

tfc

粉丝 3
博文 12
码字总数 4629
作品 0
长春
程序员
私信 提问
加载中

评论(0)

配置项目构建完成后文件移动---- Jenkins自动化部署学习笔记(三)

  在前两篇文章中,跟大家分享了在 Windows 系统上安装 Jenkins 和使用 Jenkins 进行 Android 项目的编译打包;相信可能会有人疑问,打包完成之后,我需要将 apk 文件放入指定位置怎么办。...

onestravel
2018/06/04
0
0
PHP 扩展模块--PECL

PECL 的全称是 The PHP Extension Community Library ,是一个开放的并通过 PEAR(PHP Extension and Application Repository,PHP 扩展和应用仓库)打包格式来打包安装的 PHP 扩展库仓库。通过...

Laruence
2009/01/28
1.3W
2
Injection Attacks-XML注入

注入攻击 XML注入 虽然JSON的出现实现了服务器与客户端之间的“轻量级”数据交流,但是,作为另一种流行的可行方案,许多web服务API同时还是继续支持XML。另外,除了web服务之外,XML也是许多...

OneAPM蓝海讯通
2016/03/11
26
0
file_get_contents("php://input")的使用方法

$data = filegetcontents("php://input"); php://input 是个可以访问请求的原始数据的只读流。 POST 请求的情况下,最好使用 php://input 来代替 $HTTPRAWPOSTDATA,因为它不依赖于特定的 ph...

leycau
2015/10/20
4.7K
0
文件上传漏洞及解析漏洞总结

文件上传漏洞是指用户上传了一个可执行的脚本文件,并通过此脚本文件获得了执行服务器端命令的能力。这种攻击方式是最为直接和有效的,“文件上传”本身没有问题,有问题的是文件上传后,服务...

wt7315
2016/10/25
0
0

没有更多内容

加载失败,请刷新页面

加载更多

深圳哪里可以开电脑耗材发票-中国-新闻网

深圳哪里可以开电脑耗材发票【152 * 9б 28 * 21 б9】陈生,诚、信、合、作,保、真、售、后、保、障、长、期、有、效。adb的全称为Android Debug Bri...

17060824738
15分钟前
34
0
深圳哪里可以开家具发票-中国-新闻网

深圳哪里可以开家具发票【152 * 9б 28 * 21 б9】陈生,诚、信、合、作,保、真、售、后、保、障、长、期、有、效。adb的全称为Android Debug Bridge,...

17095420210
19分钟前
39
0
Mac OS X 10.15 编译和安装 Nginx

想在自己电脑里装个 Nginx 来进行各种测试,下面是详细的过程记录: 1. 下载软件 首先建个临时目录 nginx-src 并下载所需软件的源码进行配置 mkdir nginx-srccd nginx-srcwget http://n...

红薯
今天
62
0
0228 我的潘多拉

我的潘多拉 从一个故事说起。<br />从前,有个Java程序员非常喜欢写程序,喜欢研究源码,读英文文档。但是它在一家小公司里工作,公司的技术栈很陈旧。<br /> <br />单个系统代码中含有很多的...

李福春carter
今天
18
0
OSChina 周六乱弹 —— 屁会不会传染病毒

Osc乱弹歌单(2020)请戳(这里) 【今日歌曲】 @薛定谔的兄弟 :分享洛神有语创建的歌单「我喜欢的音乐」: 《ハレハレヤ(朗朗晴天)》- 猫瑾 手机党少年们想听歌,请使劲儿戳(这里) @空格...

小小编辑
今天
77
1

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部