March 23, 2014

《中华文明外来说的各种版本》


   “中国文化西来”的论调,明末清初西方传教士东来之时就已经开始了~~~~
  【1】 手捧《圣经》,一心想把“上帝”传给中国人的西方传教士,依据《圣经》中之创世纪、乐园放逐、洪水等记载,宣称中国文化起源于西方基督教,如清初由传教士 汤若望授意、钦天监监正李祖白撰成的《天学传概》中写道:“初人子孙聚处如德亚(指犹太)。……其后生齿日繁,散走遐逖。……在中国为伏羲氏,天学固其所 以怀来也。”
  
  【2】 随着欧洲殖民主义兴起,部分外国人的文化殖民心理也随之膨胀,不承认中国古代文明有自己独立的起源。
   发端于17世纪。德国耶稣会传教士基尔什尔(A.Kircher)在其著作《埃及之谜》(1654)与《中国图说》(1667)中首次提出,中国文明出于 埃及。他认为《圣经》所载闪的子孙率埃及人来到中国。把古埃及文字传授给中国人。此后持中国文明西来说者层出不穷,一个共同特点是否认中国文明的远古,不 相信远古的中国人会创造出辉煌的文明
  
  【3】 1716年,法国阿夫朗什主教胡爱(Huet)论证中国人乃埃及人之苗裔
  
  【4】 1758年法国汉学家约瑟夫·德·古尼著书立说认为,中国人乃是从埃及殖民过来的。
  
  【5】 同时期另外两位法国的汉学家波提(M.G.Pauthier)和卢内尔曼将汉字和楔形文字进行比较,提出了中国文明和巴比伦文明有亲缘关系的说法。
  
  【6】 十九世纪六七十年代英国传教士理雅各(JamesLegge)提出了诺亚的子孙东行来到了中国之说。
  
  【7】 十九世纪后期,德国著名的地理学家李希霍芬(“丝绸之路”这个词就是他发明的)也主张“中国人是西方移入”之说。
  
  【8】 1894年,法国人拉克佩里发表《中国古文明西源说》。他以19世纪欧洲考古界对近东地区的挖掘成果为基础,提出中国文明源于两河流域古巴比伦文明,汉族 是在公元前2200左右从西亚迁来的。并先后发表多部相关著作。拉克佩里“西来说”的根据是搜寻中国早期与古巴比伦的种种相似性。主要有天文历法方面,科 技发明方面,语言文字方面, 政治制度方面,历史传说方面,
   拉克佩里关于中国文明起源于古巴比伦的观点,显然是受到当时欧洲流行的文化传播学派的有关理论的影响。文化传播学派持世界文明的单一起源论,然后就变成了 “西源论”,即认为亚非拉等非西方地区的文明或多或少是受到西方早期文明“启示”和影响的结果,这显然是殖民主义者为其扩张侵略而进行的一种赤裸裸的辩 护。
  
  【9】 1900年,两位日本业余历史学者白河次郎和国府种德将拉克伯里的“西来说”写入面向一般大众的《支那文明史》一书中,认为中国文明起源于巴比伦,并列举了古代中华在学术、文字、政治、宗教等方面多达七十多处的相似。
  
  【10】 进入民国时代,拉克佩里“西来说”在国人中仍有相当的影响,如1915年浙江学者丁谦出版《中国人种从来考》,以《穆天子传》为主要资料,来考证中国民族 西来的有关史迹。至1918年还有人撰文指出:“朔轩辕东征之迹,其必由衡山钟山复逾昆仑,而后入于中夏,繁衍其子孙民族,以肇造此泱泱古大邦。”
  清末民初一批学者信从“西来说”,所依据的中国古文献,主要是《山海经》、《穆天子传》、《列子》、《路史》等著作。上述著作毕竟神话成分大大超过历史成分,其可信性值得推敲。不经过严谨的辨伪而盲信古书,穿凿附会,结果闹出很多笑话。
  
  【11】, 瑞典地质学家安特生考察了仰韶文化。1923年,安特生发表了《中华远古之文化》一文,把仰韶文化与中亚的安诺文化进行比较时,却得出了它们有可能同出一 源的结论,并且认为最先发现的安诺彩陶早于仰韶,所以仰韶文化有可能从西方经中亚传入。这就是著名的“中华文化西来说”。
  
  【12】 最近出现的“天马流星拳”, 苏三女士,居住在北京的人类学家,著有几部关于古代文明和人类学的玄幻作品。她认为,中国文化起源于中东,来到中国的红海沿岸的古埃及人或以色列人构成了 中国的夏、商、周文化,中国汉人主要是这些人的后裔。苏三的论证大部分都是从人名地名的音、义近似上所作的分析和猜测,并无过硬的物证。比如,
   "夏后朝"由亚伯拉罕后妃Hagar(夏甲)在大约4000年前建立
   "殷"由"红色"的以扫与其妻Judith(简狄)在大约3800年前建立
   "周"就是"Jew"(犹太人),其主要建立者为以色列12支系中的"但"家族
   黄帝可能是3700年前统治古埃及的约瑟,简狄应为其伯母。。。。。。

March 11, 2014

ARM U-boot Init sequence

This is how it goes:

arch/arm/cpu/arm_cortexa8/start.s (replace cortexa8 with your CPU)

- Interrupt vectors setup
-  cpu_init_crit
- u-boot relocate
- stack setup
- call C code start_armboot, located at arch/arm/lib/board.c

But start_armboot is not the first C function called.

cpu_init_crit -> calls lowlevel_init, which is located at  under your specific CPU, such as arm_cortexa8/ti81xx/lowlevel_init.S, then a function s_init (with label s_init_start) is called. This function is a C function located at boards/ti/ti8168/evm.c

So s_init is called way earlier than start_armboot in lib/board.c


March 3, 2014

libltdl in wrong place when cross compiling

When you cross compile a software, and your cross compiler is using /usr/lib/libltdl.so instead your cross compiler's libltdl, this is how to solve it:

export LIBTOOL_SYSROOT_PATH=/opt/ezsdk/linux-devkit/arm-none-linux-gnueabi/

Fix the path above to your cross compiler's libldtl directory.

The file libltdl.la ( a text file) in my build server uses the environment variable LIBTOOL_SYSROOT_PATH to find the libltdl.so file. So make sure that environment variable is defined, not only in configure time, but also before you run  Make.

中国人到底是诺亚哪个儿子的后裔

转载, 一家之言,仅供参考:

华人基督徒多半认为咱们“炎黄子孙”同犹太人一样,是挪亚(Noah)的儿子“闪”(Shem)的后裔,但是谁也找不到证明这一说法的圣经出处。一言以蔽 之,这种说法只是根据教会传统,并不是根据圣经。本人在这里全盘否定这一说法本意并不是要掀起一个“轩然大波”;而是要以圣经为依据来陈述并与大家分享一 个尘封已久的信息:“炎黄子孙”不是“闪”的后裔,而是“含”(Ham)的后裔;更准确地说,“炎黄子孙”正是那被诅咒的“迦南”(Canaan)的后 裔。《创世纪》十章里比较详尽地记述了从挪亚的三个儿子闪、含和雅弗(Japheth)开始的世界各民族雏形和发展去向。历代以来,所有依据本章圣经进行 的人类学及人种学方面的考古或研究都能从经节中获得特别的启示和正确的引导并且大大获益。


常常遇到一个常识性偏误,就是认为含的后裔是非洲人。根据《创世纪》十章六节,含生了古实(Cush)、麦西(Mizraim)、弗(Phut)和迦南 (Canaan)四个儿子。说非洲黑人是古实的后裔没有问题,然而请不要忽略:古埃及人和非利士人(Philistines,巴勒斯坦因此得名)也是麦西 的后裔(注:埃及和麦西在希伯来语里是一个词,以色列人现在仍然把埃及称为“Mizraim”而不称为“Egypt”。)。然而古埃及文明存留下来的仅有 金字塔等建筑和一些文物;与汉语同属象形文字的古埃及语也销声匿迹了;古埃及人千百年来也已被闪系的阿拉伯人融合或同化(似乎穆巴拉克等埃及人的脸部轮廓 尚留存了一丝麦西――含系的扁平特征,金字塔里的木乃伊也非常具有“含族”的特征---脸部,尤其是鼻子扁平)。另外,在两河流域的亚述建造尼尼微等城市 的宁录(Nimrod)也是古实的后裔,以色列人的苦敌耶布斯人(Jebusite)、亚摩利人(Amorite)等等都是迦南的后裔。

《创世纪》十章十五~十八节(和合本)是这样记载的:(15)迦南生长子西顿,又生赫,(16)和耶布斯人,亚摩利人,革迦撒人,(17)希未人,亚基人,西尼人,(18)亚瓦底人,洗玛利人,哈马人,后来迦南的诸族分散了。这里的十七节提到了迦南的一个儿子西尼(Sini),Sini竟然是现代以色列人用来对我们一切华人(含港澳台胞和海外侨胞)的称呼!我三年前偶然发现了这个问题。“后来迦南的诸族分散了”这句话很有意味,尽管没有给出分散的方向。有人说Sini是“西奈人”,但希伯来语保留下来的发音在“西奈”和“西/希尼”上的区别是明显的。

与此经节呼应,见于以赛亚书四十九章十二节(和合本):“…看哪,这些从远方来:这些从北方、从西方来,这些从秦国来(“秦”原音作“希尼”)。”“希尼”的希伯来原文是前面所提及的“西尼”的复数形式(“秦国”意即“西尼人的地方”)。

针对这两处圣经节,我趁今年一、二月份在耶路撒冷希伯来大学进修现代希伯来语之际,抱着原文(古希伯来语)圣经问过不下十个母语为希伯来语的以色列人,从法官到律师到教师到学生到医生到导游所有人的回答都一样,他们直截了当地告诉我:这两个西尼(或希尼)指的就是你!就是你们中国人!!!“西尼”原文是单数Sini,指的是迦南的儿子;“希尼”原文是复数Sinim,是西尼人的复数形式。根据读音,西尼、希尼和细腻、悉尼、稀泥实 质上根本没有什么不同!用字不同的原因完全是由于翻译问题造成的。另外,古希伯来语和现代希伯来语皆称中国为“Sin”(发音确像“秦”,碰巧跟英语“罪 性”---sin读音一样,不过是个专有名词),称中国男人为Sini,称这个女人为Sinit,(复数为Sinim),称汉语(华语)为 “Sinit”。

也许是因为挪亚关于迦南所说的预言让炎黄子孙在心理上难以承受;也许有人说炎黄子孙和犹太人有惊人的相似点于是将炎黄子孙说成是“闪”的子孙就似乎没有人愿意去怀疑甚至否定了。谬误传多了传滥了传开了传久了也就很容易被当作真理来对待了。看看《创世纪》九章二十五~二十七节(和合本)是怎么说的:(25)(挪亚)就说,“迦南当受咒诅,必给他弟兄作奴仆的奴仆。(26)又说,耶和华闪的神是应当称颂的,愿迦南作闪的奴仆。(27)愿神使雅弗扩张,使他住在闪的帐棚里,又愿迦南作他的奴仆。”


你不相信炎黄子孙是被诅咒的民族吗?其实你可以翻一翻华夏历史看一看,再想一想:你真的觉得中华民族从古至今所受的诅咒还不够多不够惨吗?世界上还能有哪 个民族会像中华民族这样被“真龙天子”们折腾得伏屍遍野忍气吞声低三下四毫无脾气的?如果不愿承认“受诅咒”的事实,为何总是把“灾难深重”与“中华民 族”连在一起用呢?被雅弗后裔(英美法德等为代表)殖民的一百多年历史难道被遗忘了吗?就连那同属含系后裔的日寇不也曾用铁蹄践踏过大半个中国吗?闽粤沿 海的“侨乡”美誉不是被西洋人抓去的“猪猡”(或称“苦力”――COOLY,注意:“COOLY”就如此悲惨地成了英语的外来词!!!)的男士们用鲜血和 生命换来的吗?“横贯北美之铁路的每一根枕木下都躺卧着一个华工的冤魂”――没有听说一位正直的美国诗人曾写过这样的义愤填膺的诗句吗?还有:当年在上海 滩跟着英国人屁股后面混的“印度阿三”(也许是沾了点雅弗的血缘关系的含系后裔,被大英帝国殖民的历史还要长呢!!!)不是也敢对租界内外大清王朝的臣民 们指手画脚吗?也许他们嚷嚷“华人与狗不得入内”比当时的英国人还起劲呢!---整个一幅“奴仆的奴仆”的活图画!!!同为含系后裔的非洲大陆不也曾一度被英法葡荷等列强彻底瓜分并殖民得奄奄一息毫无生机吗?臭名昭著的黑奴贸易难道不值得雅弗的子孙们痛定思痛深刻反省吗?

“雅弗必扩张”的预言更是应验到家了:曾被含系后 裔(美洲印第安人:他们也保留了许多象形文字的文物古迹)占据几千年之久的美洲大陆几百年前被英法西葡等列强完全殖民,印第安人明明是原始主人,后来却有 了“哥伦布发现新大陆”的强盗说法!印第安人的话语权到那里去了?!美国、澳大利亚、新西兰等其实就是英国的替代者(扩张的结果)。欧洲文明鼻祖的希腊人 (以色列人对他们仍用旧约圣经的称呼“雅完”Yavan,或Iavan)至今仍然承认自己是“雅弗”的后裔。还有,特别喜欢扩张的俄国人(旧约称为“罗 示” Rusi)也是雅弗的后裔,仅十九世纪就从清朝政府手中割去一百五十多万平方公里的领土!如今的俄国首都虽远在莫斯科,却能控制广袤的西伯利亚的北极、东 端和南界。再想想含系的一代天骄成吉思汗及其儿孙们虽然也有打到莫斯科的历史记录,如今的蒙古国却在中俄两国的夹缝中生存,辉煌不再!在这里略微提一下: 把基督教称为“洋教”的说法其实非常非常的外行:圣经(包括旧约和新约全部六十六本书)的几十位作者除了一个路加(注:《路加福音》和《使徒行转》二书的 作者)是希腊医生之外,全部都是犹太人!福音(救恩)首先临到的是犹大人而根本不是“西洋人”;相反,是使徒保罗(希伯来人生的希伯来人)把福音传到了欧 洲。欧洲(包括后来的美洲)一千多年以来基督徒比例较高的事实正是“住在闪的帐棚里”这话的应验。


若反问为什么历史上强大的中国曾经也大大地扩张,并拥有附庸国一大堆,怎么解答?
是的,没错!不过这些“扩张”全是在含系的土地上:东夷南越西戎北胡都是 含系后裔,也就是说,蒙藏壮羌都是属含的。大明王朝的郑和七下西洋除了给蛮夷之邦送送温暖之外还给世界留下什么了呢?至于汉族和汉朝的“汉”,韩国的 “韩”还有“汉城”(注:近年才被“去中国化”之心极强的韩国人改成“首尔”,但韩国人也毫无疑问是“含”的后裔)的“汉”与那个挪亚之子“含”有没有必 然联系目前还没有特别的考证。然而根据三星堆遗址发现的文物就可以推断:成都平原三千年前的文明与两河流域的文明极可能有很大的内在关系。两河流域是一个 闪、含系民族长期混居的地方,闪系的亚伯拉罕就是离开了含系聚居的偶像之邦迦勒底之后才去应许之地的,所以被称为“希伯来人”--“越过(河)的人”。亚 伯拉罕是犹太人和阿拉伯人共认的祖先,只是阿拉伯人将这同一个人读作“易不拉欣”而已,如同把雅各读作“雅各布”,约瑟读作“尤素福”一样。


如果说炎黄子孙是闪的后裔,那么“闪的神”这个说法就实在不对了!炎黄子孙里没有多少人(百分比极低)认识闪的神;相反,对于来自牛鬼蛇神之邦(指印度)的偶像倒是趋之若鹜!也许轩辕黄帝所祭拜的“天”还和“闪的神”有 关系,但是他的子孙们后来却自称为“龙的传人”了。本文在这里不讨论关于中华民族“龙图腾”的问题。其实越南人也十分想自称为“龙的传人”呢!甚至中国和 印度之间的小国不丹(好像没有人认为这个国家有多重要)更干脆:国旗中间就是画了一个和中国人想象中一模一样的一条龙!关于新约最后一卷书《启示录》十二 章所指的“大红龙”、“大龙”、“古蛇”、“魔鬼”、“撒但”指的是谁,智者见智,仁者见仁。现存的闪系主要民族如犹太人(与希伯来人、以色列人的称呼有 交叉又有区别)、阿拉伯人、伊朗人(波斯人)倒是正如挪亚所预言:只虔诚敬拜一个神。

中国人的祖先

公元前2458年挪亚方舟时代肆意了一年毁灭全地的大洪水退去之后,挪亚的三个儿子(闪、雅弗、含)就被分散迁徙了。如今大部分的阿拉伯人、犹太人、波斯 人是闪氏一族的后裔。雅弗的子孙多分布在如今的欧洲西北等地,包括英、法、德、意、葡、俄;当然几百年前被英国人占领,如今被白种人统治的美洲、澳大利 亚、新西兰(这些土地原是被含系后裔占领长达几千年之久的,如美洲印第安人)也是雅弗一族的。我感兴趣的是含系子孙。含有四个儿子,古实、麦西(也称埃 及)、弗、迦南。他们绝大部分分布在非洲、地中海、西亚等地,也有包括日本、印度、中国在内的远东太平洋岛屿部落。像非洲的黑人如俄塞俄比亚被考证是古实 的后裔,麦西是古埃及人的祖先,现今的利比亚是弗一族的。而中国人及部分以色列人则是迦南一支的。迦南的其中一个儿子叫西尼(Sini),据母语为希伯来 语的以色列各学者指出,西尼就特指包括港澳台在内的华人的总称。

在中国的学术界,神农即是闪(Shem)、黄帝是含(Ham)、炎帝就是雅弗(Japheth)了。他们是大洪水前100年即在挪亚(NOAH, 即女娲)500岁时生的。而挪亚(女娲)是玛土撒拉(伏羲)的孙子,也是亚当(Adam,即少典)和夏娃(Eve,即有娲)的第十代。要指出的是,中国人 并不是‘炎黄子孙’,我们其实是黄帝的后裔。因此以上述为根据的结论就很明了了,人类有个共同的祖先,就是公元前4114年被造的亚当和夏娃。亚当享年 930岁。《圣经-创世记》的第十章开始比较详细地记述了由挪亚的三个儿子开始的世界各部落的雏形和发展去向。

二.挪亚的三个儿子:

圣经内容引用: 创世记9:25-27
『迦南当受咒诅,必给他弟兄做奴仆的奴仆』
『耶和华闪的神,是应当称颂的,愿迦南作闪的奴仆』
『愿神使雅弗扩张,使他住在闪的帐棚里,又愿迦南作他的奴仆』

这就是挪亚基于对他三个儿子观察后,对他们子孙后裔的著名的预言。
著名圣经人类学者Arthur C. Custanc在他的五部专著之一《挪亚的三个儿子》中说明,人类三个基本层次的需求――灵(信仰层面)、体(物质层面)和智(精神/文化层面,)――是 如何由神命定而被挪亚一家的这三个分支来分担。历史已经用显著的方式证明了各个人种在各自杰出成就上的专特性。就挪亚的三个儿子来说,含的兴趣主要在于体 (科技、生活基本需求),雅弗在他的智力特征(学术、哲学、文化)上充分表现了他的天赋,闪则追求信仰层面。

漫长的人类历史已经逐步验证了挪亚的预言:『耶和华闪的神是应当称颂的』无疑藉此预言闪系将承担传扬真神上帝的任务。犹太教,伊斯兰教,与基督教都是一神 教,都是闪系一族所宣扬的。而在公元元年降为肉身的主耶稣也是闪系后裔。『愿神使雅弗扩张,使他住在闪的帐棚里』,这里的扩张意指在文化、学术、科学方面 影响世界;当然进行这些智力扩张的前提是先要有政治占领来支持的。挪亚说,使雅弗『住在闪的帐棚里』很确切地告诉我们,雅弗的后裔将分享与闪氏一样的属灵 信仰。十几个世纪以来大部分欧洲各国、以及如今的美洲各国都信奉上帝教,从这里就可以很好地验证。至于含的儿子『迦南当受咒诅』,给他弟兄做奴仆的奴仆, 以及做闪和雅弗的奴仆,很多学者认为,相对于闪和雅弗在属灵和学术上的贡献,含在于科技以及生活所需方面的贡献并非与他们有价值大小的差别,也并非真指仆 役。在含系中,最先的印刷术,航海术,文字,金属业以及衣食住行等基本生活层面上的发明创造为世界发展提供了基础的保障。
本人的观点与顶级圣经人类学者Arthur C. Custance一致。他著有《挪亚的三个儿子》(“Noah's Three Sons”)等圣经人类学丛书)


February 28, 2014

wpa_supplicant with DoD PIV / CAC card

EAP-TLS and EAP-PEAP/MS-CHAPv2 authentications

For EAP-TLS, you will need to read the cert from the PIV card to a local file. You  can use the following command:
pkcs11-tool --module /usr/local/lib/opensc-pkcs11.so -r -y cert -d 01 -o cac-cert.der

wpa_supplicant.conf:

ctrl_interface=/var/run/wpa_supplicant
eapol_version=1
#ap_scan=1
#fast_reauth=0
pkcs11_engine_path=/usr/lib/ssl/engines/engine_pkcs11.so
pkcs11_module_path=/usr/local/lib/opensc-pkcs11.so

network={
    ssid="test"
    key_mgmt=WPA-EAP
    eap=PEAP
    proto=RSN
    pairwise=CCMP
    group=CCMP
    identity="myname"
    password="mschappass"
    ca_cert="CA.pem"
    phase1="peaplabel=0"
    phase2="auth=MSCHAPV2"
    priority=10
}

network={
    ssid="test-tls"
    key_mgmt=WPA-EAP
    eap=TLS
    proto=RSN
    pairwise=CCMP
    group=CCMP
    identity="john@abctech.com"
    ca_cert="CA.pem"
    client_cert="cac-cert.der"
    priority=10
    engine=1
    engine_id="pkcs11"
    key_id="1:01"
    pin="77777777"
}

#PEAP-EAP-TLS-SMARTCARD
network={
    ssid="test-peap-eap-tls"
    key_mgmt=WPA-EAP
    eap=PEAP
    proto=RSN
    pairwise=CCMP
    group=CCMP
    anonymous_identity="noname@noname.com"
    ca_cert="/etc/CA.pem"
    identity="sean"
    client_cert2="/tmp/cac-cert.der"
    phase1="peapver=0"
    phase2="auth=TLS"
    priority=10
    engine2=1
    engine2_id="pkcs11"
    key2_id="1:01"
    pin2="77777777"
}

#key_id 1:01 means card reader at slot #1, and key id 01 on the card

To convert JTIC CA files to PEM format:

openssl pkcs7 -print_certs -in Certificates_PKCS7_v4.0.1_JITC.pem.p7b -out JITC-CA.pem


To Valid pin, have the card sign a simple file:

pkcs11-tool --sign  -m SHA1-RSA-PKCS --input-file /etc/passwd --output-file /tmp/signature --pin 12345678

If signed successfully, then the pin is correct.



---Just for testing purpose---

To test your openssl engine

run: openssl, then


> engine -vvvv dynamic -pre SO_PATH:/usr/lib/ssl/engines/engine_pkcs11.so \
-pre ID:pkcs11 -pre LIST_ADD:1 -pre LOAD -pre VERBOSE \
-pre MODULE_PATH:/usr/local/lib/opensc-pkcs11.so  

> req -engine pkcs11 -new -key 1:01 -keyform engine -x509 -out cert.pem -text

it will ask you for the PIN, and should generate a cert.pem if everything works.


------------Hostapd (including functioning as WiFi AP and RADIUS server)-----
hostapd.conf:
interface=wlan0
logger_syslog=-1
logger_syslog_level=2
logger_stdout=-1
logger_stdout_level=2
ctrl_interface=/var/run/hostapd
ctrl_interface_group=0
ssid=test-tls
hw_mode=g
channel=1
beacon_int=100
dtim_period=2
max_num_sta=255
rts_threshold=2347
fragm_threshold=2346
macaddr_acl=0
auth_algs=3
ignore_broadcast_ssid=0
wmm_enabled=1
wmm_ac_bk_cwmin=4
wmm_ac_bk_cwmax=10
wmm_ac_bk_aifs=7
wmm_ac_bk_txop_limit=0
wmm_ac_bk_acm=0
wmm_ac_be_aifs=3
wmm_ac_be_cwmin=4
wmm_ac_be_cwmax=10
wmm_ac_be_txop_limit=0
wmm_ac_be_acm=0
wmm_ac_vi_aifs=2
wmm_ac_vi_cwmin=3
wmm_ac_vi_cwmax=4
wmm_ac_vi_txop_limit=94
wmm_ac_vi_acm=0
wmm_ac_vo_aifs=2
wmm_ac_vo_cwmin=2
wmm_ac_vo_cwmax=3
wmm_ac_vo_txop_limit=47
wmm_ac_vo_acm=0
ieee8021x=1
eapol_key_index_workaround=0
eap_server=1
eap_user_file=hostapd.eap_user
ca_cert=./JITC-CA.pem
server_cert=./hostapd.server.pem
private_key=./hostapd.server.key
private_key_passwd=mypass
own_ip_addr=127.0.0.1
auth_server_addr=127.0.0.1
auth_server_port=1812
auth_server_shared_secret=radiussecret
radius_server_clients=./hostapd.radius_clients
radius_server_auth_port=1812
wpa=3
wpa_key_mgmt=WPA-EAP
wpa_pairwise=CCMP
rsn_pairwise=CCMP



hostapd.eap_user:

#john uses EAP-TLS and PEAP, everyone else uses PEAP and MSCHAPv2
"john@abctech.com"        TLS
* PEAP
"john"        MSCHAPV2        "mschappass"    [2]

hostapd.radius_clients:
# RADIUS client configuration for the RADIUS server
127.0.0.1 radiussecret

openssl how to add a config section

use this: (The magic is in the keyword openssl_conf which is recognized by openssl)

openssl_conf = openssl_def

[openssl_def]
engines = engine_section

[engine_section]

foo = pkcs11_section

[pkcs11_section]
dynamic_path = /usr/local/lib/engine_pkcs11.so
engine_id = pkcs11
default_algorithms = ALL
#default_algorithms = RAND,RSA
init = 1

PEAP certificates, signing requirements and examples


There are only minor differences between standard SSL certificates used by secure web sites and those
used with PEAP on 802.1x wireless networks.

With PEAP the SID of the network, rather than your organizations domain must match the common name
(cn) of the certificate.  Additionally an EKU (Enhanced Key Usage) for Server Authentication (OID
1.3.6.1.5.5.7.3.1) must be specified when creating your public certificate or signing request.

[ PEAP ]
extendedKeyUsage = 1.3.6.1.5.5.7.3.2
extendedKeyUsage = 1.3.6.1.5.5.7.3.1

[ clientAuth ]
extendedKeyUsage = 1.3.6.1.5.5.7.3.2

[ serverAuth ]
extendedKeyUsage = 1.3.6.1.5.5.7.3.1


In these examples we will use the OpenSSL utility to create a Certificate Signing Request (CSR) used with a third party certificate authority such as Verisign or Thawte.  We will also generate a ‘self-signed’ certificate that does not require a certificate authority but does require users to first accept your certificate as valid on a one time basis depending on the supplicant and its configuration.


Example creating a certificate signing request for a certificate authority
openssl req -new -nodes -keyout private.pem -out public.csr -extensions PEAP -config openssl.cnf

The output file public.csr is processed by your certificate authority (CA), which will return a signed
certificate file to you.  Combine private.pem with the certificate returned from the CA into a single file.  This file becomes the  ‘PEAP Certificate’ file.  You will likely also need the CA’s certificate chain file if one is required.  This file becomes the ‘PEAP CA Certificate’.


Example creating a ‘self-signed’ certificate

openssl req -new -x509 -key private.pem -out public.pem -extensions PEAP -config openssl.cnf -days 5000

February 19, 2014

qt with gif support

Put the plugin libqgif.so under <executable dir>/imageformats/libqgif.so

libqgif.so should be under QT-SRC/plugins/imageformats

February 14, 2014

Linux AF_PACKET raw socket incoming and outgoing

In Linux, one use socket(family, type, protocol) to create a socket.  Some tips about raw socket:

1. To capture packets with Ethernet header, use family AF_PACKET

2. PF_PACKET is the same as AF_PACKET. Actually PF_* is the same as AF_*. AF_ prefix is the new way of calling them. (Address Family)

3. When using PF_PACKET,  type can either be SOCK_RAW or SOCK_DGRAM

4. protocol can be ETH_P_IP, ETH_P_ALL, etc. The complete list is under Linux source tree include/uapi/linux/if_ether.h

5. IMPORTANT ETH_P_ALL captures all incoming and outgoing packets. Other protocols only capture incoming packets. (See this question: http://stackoverflow.com/questions/20864962/does-capturing-outgoing-frames-using-linux-raw-socket-requires-eth-p-all)

Also remember to bind the raw socket to the particular network interface. Man 7 af_packet for details.

February 13, 2014

Change TI Sitara DM816x CPU Speed

Variables:

fr=27Mhz ,

Variables defined in U-boot source code:
P=1,
N=64
FREQ integer part = 0x0B
FREQ float part = 0x851EB7 (the maximum if 0xFFFFFF), so 0x851EB7 is around 0.52

fvco=(N/P)*fr=64*27MHz = 1728MHz
fs=(fvco*k)/FREQ, where k=8 (always)
   = (1728*8)/11.52=1200MHz

You can tweak FREQ (integer and float part) to adjust CPU frequency.

For example, setting it to 15 (FREQ.integer=0x0E, FREQ.float=0) will change the CPU speed to 987Mhz.

The theoretic maximum is around 1500Mhz, but the TI tested max speed is 1200MHz.

February 7, 2014

Linux switch_root vs pivot_root vs chroot

1. pivot_root can/should be used together with chroot
     
       pivot_root new_root put_old
       pivot_root moves the root file system of the current process to the
       directory put_old and makes new_root the new root file system.  

       cd new_root
       pivot_root . old-root
       exec chroot . command
       umount /old-root
Note that chroot must be available under the old root and under the new root, because pivot_root may or may not have implicitly changed the root directory of the shell.

2. switch_root newroot init [arg...]
       switch_root moves already mounted /proc, /dev and /sys to newroot and
       makes newroot the new root filesystem and starts init process. switch_root       is typically used with initramfs

       WARNING: switch_root removes recursively all files and directories on
       the current root filesystem.
     
The following shell script fragment demonstrates how to use switch_root:
  # First, find and mount the new filesystem.
  mkdir /newroot
  mount /dev/whatever /newroot

  # Unmount everything else you've attached to rootfs.  (Moving the filesystems
  # into newroot is something useful to do with them.)

  mount --move /sys /newroot/sys
  mount --move /proc /newroot/proc
  mount --move /dev /newroot/dev

  # Now switch to the new filesystem, and run /sbin/init out of it.  Don't
  # forget the "exec" here, because you want the new init program to inherit
  # PID 1.

  exec switch_root /newroot /sbin/init

February 5, 2014

css z-index

The Natural Stacking Order

In an HTML page, the natural stacking order (i.e. the order of elements on the Z axis) is determined by a number of factors. Below is a list showing the order that items fit into a stacking context, starting with the bottom of the stack. This list assumes none of the items has z-index applied:
  • Background and borders of the element that establish stacking context
  • Elements with negative stacking contexts, in order of appearance
  • Non-positioned, non-floated, block-level elements, in order of appearance
  • Non-positioned, floated elements, in order of appearance
  • Inline elements, in order of appearance
  • Positioned elements, in order of appearance
The z-index property, when applied correctly, can change this natural stacking order.
Of course, the stacking order of elements is not evident unless elements are positioned to overlap one another. Thus, to see the natural stacking order, negative margins can be used as shown below:
Grey Box
Blue Box
Gold Box
The boxes above are given different background and border colors, and the last two are indented and given negative top margins so you can see the natural stacking order. The grey box appears first in the markup, the blue box second, and the gold box third. The applied negative margins clearly demonstrate this fact. These elements do not have z-index values set; their stacking order is the natural, or default, order. The overlaps that occur are due to the negative margins.

Why Does it Cause Confusion?


Although z-index is not a difficult property to understand, due to false assumptions it can cause confusion for beginning developers. This confusion occurs because z-index will only work on an element whose position property has been explicitly set to absolute, fixed, or relative.

Source: http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/

February 3, 2014

how to make samba follow symbolic links

Make sure you have the following in your smb.conf file

1. in [global] section, add
    unix extensions = no

2. in your particular directory section add
    follow symlinks = yes
    wide links = yes

Restart smbd service and you should be good to go

January 27, 2014

PIV card and Linux

Goal: 
  1. Program a blank Gelmalto PIV card ( Protiva PIV CARD v1.55 DL) so that it contains a certificate, using the RSA keypair generated by the card
  2. Have Linux wpa_supplicant use the certificate in the card to perform EAP-TLS authentication

Card Programming:
Approach 1: Use the NIST PIV card test software
  1. Download the software from: http://csrc.nist.gov/groups/SNS/piv/download.html
    1. You need both the “SP 800-73 Reference Implementation” and the “PIV Data Generator and PIV Data Loader”
  2. Get Java JRE if you don’t have
  3. unzip both of them to a folder, in my case c:\tools\pivcard
    1. Open a “Cmd” windows as Administrator,
    2. cd \tools\pivcard\PIV Middleware\Binaries
    3. install.bat
    4. copy c:\windows\system32\piv.dll  ..\..\ PIV_Test_Data_Software\Binaries
  4. Now you can run the program PIV_Test_Data_Software\Binaries\ PIV Data Loader.exe to write to the card; and use the program JPIV Test Data Generator.jar to generate the data
  5. To piv data loader needs the data from the data generator. Some data generator tips:
    1. Goto “Crypto Provider”, and point it to your root keystore. If you don’t have one, you can use “keystore explorer” software (open source) to create one, and then create a key-pair, and make it a self-signed root CA. (use standard JKS format).
    2. The CA Alias is your CA’s name
    3. The content signer’s alias can be the same as your CA’s alias.
    4. Now put something random in fields of tab CHUID. GUID has to be 16 chars
    5. Under “Certificates tab”, pick “piv auth cert”, “valid from” and “valid to” is in the format of “YYYYMMDDHHMMSS”.
    6. Choose “get public key from file”. This file should be generated by the piv loader program, under “asymmetric key pair”.
    7. Now hit generate, and check console there is no error, and then “Save”
  6. The saved certificate format is weird. It adds a header and footer around the standard “DER” format.
    1. It adds 0x “30 82 LEN1 LEN2” as header. 0x30 in DER format means “sequence of”.  “82 LEN1 LEN2” is the “long form” of the “definite form” encoding of the length.  For “Signature Certificate”, the header is “70 82”.
    2. It also adds a footer of 5 bytes “71 01 00 fe 00”, means “application” tag, “set or set of”, length of 1, content of 00. Then another tag “fe”, meaning “private tag” of 0 byte.
    3. If you want to generate your own certificate instead of using the data generator, I suppose you could generate a DER format certificate, and then wrapper it with header and footer above, then burn to the card using the data loader application. I have not tried this yet.

Approach 2: Use piv-tool inside opensc-tools (piv-tool itself did not work well for me)

  1. Use opensc-tools 0.12.2 or newer
  2. To read the certificate of the card, use:
    1. pkcs11-tool --module=/usr/lib/i386-linux-gnu/opensc-pkcs11.so -r -y cert -a "Certificate for PIV Authentication" > mycert.der (using label to read)
    2. OR, pkcs11-tool --module=/usr/lib/i386-linux-gnu/opensc-pkcs11.so -r -y cert -d 01 -o my.cert (using id to read)
    3. To list all the data objects, use: pkcs11-tool --module=/usr/lib/i386-linux-gnu/opensc-pkcs11.so –O

Wpa_supplicant
# OpenSSL Engine support
# These options can be used to load OpenSSL engines.
# The two engines that are supported currently are shown below:
# They are both from the opensc project (http://www.opensc.org/)
# By default no engines are loaded.
# make the opensc engine available
#opensc_engine_path=/usr/lib/opensc/engine_opensc.so
# make the pkcs11 engine available
#pkcs11_engine_path=/usr/lib/opensc/engine_pkcs11.so
# configure the path to the pkcs11 module required by the pkcs11 engine
#pkcs11_module_path=/usr/lib/pkcs11/opensc-pkcs11.so

It seems that engine_opensc is the old version. The current version should be pkcs11_engine. Opensc-pkcs11.so is the PKCS11 library to access the smartcard.

OpenSC installation under GNU|Linux

  • Communication with smartcard reader is managed by pcsc + libccid.
  • Smartcard drivers and PKCS#11 library is managed by opensc

installing pcsc + libccid + opensc

Modern smartcard readers are CCID compliant.  GNU/Linux can only handle CCID readers. It is recommended to use libccid >= 1.4.5.
$ apt-get install pcscd libccid libpcsclite1 opensc
 
Some important files:
/usr/lib/i386-linux-gnu/opensc-pkcs11.so uses
/usr/lib/i386-linux-gnu/libopensc.so.3, which uses
/usr/lib/i386-linux-gnu/libpcsclite.so.1.0.0
Make sure to add your own user to the pcscd group:
$ adduser foo pcscd

January 24, 2014

PIV CAC card list of certificates

Question:
SP 800-73 Part 1 defines four X.509 certificate data objects and there are key references for asymmetric keys given. One assumes that:

Key Reference 9A <==> X.509 Certificate for PIV Authenication
Key Reference 9B <==> X.509 Certificate for Card Authentication
Key Reference 9C <==> X.509 Certificate for Digital Signature
Key Reference 9D <==> X.509 Certificate for Key Management

is this correct?

Furthermore, it is not stated for which of these key pairs the private key is resident on the card and for which key pairs the private key is held outside the card.
Answer:
The correct relationship is as follows:

Key Reference 9A <==> X.509 Certificate for PIV Authentication. The 9A private key is held on the card.

Key Reference 9B: The Card Management Key (aka Card Application Administration Key) is a symmetric key and has no certificate. The 9B symmetric key is held on the card.

Key Reference 9C <==> X.509 Certificate for Digital Signature. The 9B private key is held on the card.

Key Reference 9D <==> X.509 Certificate for Key Management. The 9D private key is held on the card.

Key Reference 9E <==> X.509 Certificate for Card Authentication Key. Note that the Card Authentication Key may be asymmetric or symmetric. It has a certificate only if it is asymmetric. The private or secret 9E key is held on the card.

January 20, 2014

The novel way to build cross compiler tools

http://www.cis.upenn.edu/~milom/cross-compile.html

The reason it is novel is because it takes the target header file and library directly without recompiling them. Therefore this approach is much simpler than the regular from scratch method.

How to Cross-Compile GCC for SPARC Solaris

Computer and Information Sciences Department
University of Pennsylvania
January 2010
To make it easier for my CIS534 students to compile code for our one and only SPARC machine (a 128-thread Niagara T2 box, generously donated by Sun Microsystems), I created a cross-compiler for GCC on x86/Linux to SPARC/Solaris. This page documents how I did it. I'm putting it on-line in case anyone else finds it helpful.

Overview

There are three steps to building the cross compiler:
  1. Specifying the configuration and paths
  2. Finding and installing the proper system header files and libraries
  3. Cross-compiling GNU binutils and GCC

Definitions and Configuration

  • The "host" is the machine on which the compiler executes (x86/Linux in my case). By default, the configure scripts will automatically figure this out.
  • The "target" is the machine on which the output binaries will execute (for SPARC/Solaris in my case, it should be sparc-sun-solaris2.10). This needs to be set explicitly. You can find out the proper target string by executing gcc -dumpmachine.
  • The "prefix" is the instalation prefix where the cross-compiler will be installed.
  • The "sysroot" is the location the cross compiler will look for header files and libraries. The sysroot directory acts as if it is the root of the system,. So, for example, header files go in $SYSROOT/usr/include/ and library files go in $SYSROOT/usr/lib/, etc.
I set these options using environment variables:
setenv TARGET sparc-sun-solaris2.10
setenv PREFIX /mnt/castor/seas_home/c/cis534/public/cross/
setenv SYSROOT $PREFIX/sysroot/
set path = ( $path $PREFIX/bin )

mkdir $PREFIX
mkdir $SYSROOT

System Headers and Libraries

To be able to build and link applications, the cross-compiler needs access to the system header files. As building the compiler also uses some of these files, installing these files needs to be done first. If you have access to the target machine, you can just copy the files into $SYSROOT. Otherwise, you'll need to download the files from the proper distribution. To copy the files, I piped tar through SSH to the SPARC machine (arachnid, in our case), as I could not find an option to get SCP to preserve symbolic links:
cd $SYSROOT
ssh milom@arachnid.seas.upenn.edu "tar -cf - /usr/include" | tar -xvf -
ssh milom@arachnid.seas.upenn.edu "tar -cf - /usr/local/include" | tar -xvf -
ssh milom@arachnid.seas.upenn.edu "tar -cf - /lib" | tar -xvf -
ssh milom@arachnid.seas.upenn.edu "tar -cf - /usr/lib" | tar -xvf -
ssh milom@arachnid.seas.upenn.edu "tar -cf - /usr/local/lib" | tar -xvf -
Copying the above directories worked for what I needed to do, but you might also considering copying additional headers and libraries:
ssh milom@arachnid.seas.upenn.edu "tar -cf - /usr/openwin/include" | tar -xvf -
ssh milom@arachnid.seas.upenn.edu "tar -cf - /usr/dt/include" | tar -xvf -
ssh milom@arachnid.seas.upenn.edu "tar -cf - /usr/X11/include" | tar -xvf -
ssh milom@arachnid.seas.upenn.edu "tar -cf - /usr/openwin/lib" | tar -xvf -
ssh milom@arachnid.seas.upenn.edu "tar -cf - /usr/dt/lib" | tar -xvf -
ssh milom@arachnid.seas.upenn.edu "tar -cf - /usr/X11/lib" | tar -xvf -

Cross-compiling GNU binutils and GCC

Building binutils and GCC is reasonable straightforward (if everything works), by downloading, unpacking, configuring, running make, and then make install for both:
mkdir /scratch/users/build
cd /scratch/users/build

wget http://ftp.gnu.org/gnu/binutils/binutils-2.20.tar.gz
tar -xvzf binutils-2.20.tar.gz
mkdir build-binutils
cd build-binutils/
../binutils-2.20/configure -target=$TARGET --prefix=$PREFIX -with-sysroot=$SYSROOT -v
make all; make install

wget http://ftp.gnu.org/gnu/gcc/gcc-4.4.2/gcc-4.4.2.tar.gz
tar -xvzf gcc-4.4.2.tar.gz
mkdir build-gcc
cd build-gcc
../gcc-4.4.2/configure --target=$TARGET --with-gnu-as --with-gnu-ld  --prefix=$PREFIX -with-sysroot=$SYSROOT --disable-libgcj --enable-languages=c,c++ -v
make all; make install
You can delete the build directories once the make install has been completed. Also, the above config for GCC will only build C and C++, but you can remove that option if you need to build GCC with support for other languages.

Testing

This will create two sets of binaries. The directory $PREFIX/bin/ will include executables of the form: sparc-sun-solaris2.10-gcc. You should be able to use this to compile a program:
$PREFIX/bin/sparc-sun-solaris2.10-gcc hello.c -o hello
Running file hello should return something like:
ELF 32-bit MSB executable, SPARC32PLUS, V8+ Required, version 1 (SYSV), dynamically linked (uses shared libs), not stripped
Then copy hello over to the SPARC box, and see if it runs. Although it shouldn't be necessary, if it gives dynamic linking errors, you could try setting the LD_LOAD_LIBRARY environment variable.
Update (April 2010): If you're getting dynamic linking errors, particularly with C++, you may need to use the "-R" option when compiling. This option specifies a path the dynamic loader on the target to look for the libraries:
$PREFIX/bin/sparc-sun-solaris2.10-gcc -R $PREFIX/$TARGET/lib/sparcv9/ hello.c -o hello
This assumes the -R path is mounted on the target machine. If not, you may need to copy over those files and adjust the -R path accordingly.

January 16, 2014

serial port to tcp redirection and terminal emulation

Usually, when you connect to a serial port, on Windows, you would use Tera Term, or Putty, (or secureCRT, etc), and on Linux you would use picocom, minicom, etc. All these program do at least two things:

1. connect to a serial device
2. emulate a terminal (VT100, etc)

Now if  you want to remotely access that serial port, and you can use a program to convert the serial data stream to TCP data stream (ser2net/remserial on Linux, com2tcp on Windows). The only thing is that you still need a "terminal emulator" to get full capability (vi, etc) from that console.

One way to do it to use "putty", and use "raw tcp" and make sure you set "local echo" to "off", and "local line editing" to off on the "Terminal" tab of the Settings.


Another way is to run a local tcp-to-com kind of program. On linux, you can use remserial to create a virtual com port, and on Windows I think you can use com2tcp/com0com to do it. But I think using putty  to access it directly is easier.

com2tcp tips

com2tcp can be used on Windows to redirect UART port to TCP port. Here is an example command to do that:

     com2tcp --baud 9600 --ignore-dsr \\.\com1 8888


Note that "--ignore-dsr" is needed most of the times, otherwise com2tcp may close tcp ports when it detects DSR off.

January 15, 2014

kermit file transfer and u-boot

I usually use "picocom" on Linux to talk through a serial line to U-boot. Of course I have used "minicom" before but it seems heavy. There is even "microcom". However, so far I have stayed away from "kermit" just because it seems to be so complicated and not totally free in license.

Now the authors in Columbia University has made it totally free (BSD license), and U-boot supports its file transfer protocol (loadb command) (u-boot does not support ZModem, only Ymodem). I take a look at it.

It looks like a nice serial terminal emulator with file transfer capability. The macro part is really handy. Below is my .kermrc file with two user-defined macros for uploading uboot and kernel images using the kermit protocol in a different baud rate than console baud

cat ~/.kermrc
set line /dev/ttyUSB1
set speed 115200
set carrier-watch off
set handshake none
set flow-control none
robust
set file type bin
set file name lit
set rec pack 1000
set send pack 1000
set window 5
set delay 1
connect
define sendb {
        set speed 230400
        output \x0D
        output \x0D
        send u-boot.bin
        input 1 "NEVER"
        set speed 115200
        output \x1B
        output \x0D
}
define sendk {
        set speed 230400
        output \x0D
        output \x0D
        send uImage
        input 1 "NEVER"
        set speed 115200
        output \x1B
        output \x0D
}

January 10, 2014

Qt, embedded Linux, Keyboard map

If you happen to use Qt for your embedded Linux project, and need keyboard support. The following things may be useful.

1. Qt supports keyboard keymap since version 4.6. By default it uses the default keymap,  which has a bug (unfixed as of early 2014) that prevents CAPS LOCK and num lock to work. See details here: https://bugreports.qt-project.org/browse/QTBUG-9843 . You can either patch it using the patch file on that bug report , or use an external keymap file.

2. To use an external keymap file, you need to obtain the Linux keymap file package (http://lct.sourceforge.net/data.html click on "Download" on the left),  untar it, get "keymaps/i386/qwerty/us-latin1.kmap". This file is for the default US keyboard. Use the keymap that matches your keyboard.

3. Qt includes a tool named "kmap2qmap" to convert the above kmap file to a qmap file that Qt applications can uses. You may want to patch the "kmap2qmap" source code to prevent this bug. It's a simple patch. Then run it as "kmap2qmap us-latin1.kmap us.qmap", and you should get the new file "us.qmap". It is safe to ignore the warnings.

4. Put this qmap file in your system, let's assume "/opt/us.qmap", and set the following env variable:
export QWS_KEYBOARD="<driver>:keymap=/opt/us.qmap".  I use a qt keyboard driver plugin in my setup so I don't use the variable, but this is supposed to be how your run it. More details here.

That's it. Now your new keyboard should work. :-) I know, finally!

P.S. this website (and this one) provides good information on keyboard scan code (Set 1, Set 2, Set 3, USB HID, etc)

msed - multiple search and replace on a file from command line

msed is a simple command-line program that search and replace multiple words in a file. You put the words to be searched and replaced in the "Pattern" file, and the run msed with "msed Pattern-file Target-file".

msed does word boundary replacement. Therefore, when you ask it to replace "kit" to "kat", it will respect and not replace "kitty" or "kit0".
msed will output to standard output. You can redirect it to a file.
The code:


#!/usr/bin/php

# Perform multiple search and replace on the target file

function usage(){
    echo "\n" .
         "Usage:  msed   [-r]\n" .
         "pattern-file contains lines of Search and Replace, example\n" .
         "   Pig Dog\n" .
         "   Cat Kitty\n" .
         "-r: reversed pattern file, ie. Replace is first, Search is second\n";
}

if (count($argv)!=3 && count($argv)!=4){
    usage();
    exit(-1);
}

$pfile=$argv[1];
$tfile=$argv[2];
$reverse=false;
if (count($argv)==4){
    $reverse=true;
    fprintf(STDERR,"reversed serach and replace patterns\n");
}

## check files
$pat_str=file_get_contents($pfile);
if ($pat_str===FALSE){
    die("Error opening pattern file $pfile\n");
}
$t_str=file_get_contents($tfile);
if ($t_str===FALSE){
    die("Error opening target file $tfile\n");
}
$pat_arr=explode("\n",$pat_str);
if (count($pat_arr)<1){
    die("Error, no pattern found in file.\n");
}

## read patterns and sort by length
$pat=array("s"=>array(),"r"=>array());
foreach($pat_arr as $pline){
    $pline=trim($pline);
    if (strlen($pline)<1) continue;
    $parts=preg_split('/\s+/',$pline);
    if (count($parts)!=2){
        fprintf(STDERR,"skipping invalid pattern line:$pline\n");
        continue;
    }
    if ($reverse){
        $pat["s"][]="/\b$parts[1]\b/";
        $pat["r"][]=$parts[0];
    }else{
        $pat["s"][]="/\b$parts[0]\b/";
        $pat["r"][]=$parts[1];
    }
}

## do search and replacement
$t_str=preg_replace($pat["s"],$pat["r"],$t_str);
echo($t_str);
                

January 9, 2014

Linux USB and USB keyboard driver debugging tips

1. USBMON is your friend. It has very little dependency and is very useful in giving you low level USB packets.  The short but complete and helpful documentation is at: https://www.kernel.org/doc/Documentation/usb/usbmon.txt

2. The USB Made Simple website with details of how USB works. The articles are fairly short so you can read and understand how USB works. Very useful. Site: http://www.usbmadesimple.co.uk/ums_3.htm

3. Linux Device Driver boot (Rev 3) has a good chapter about USB Urbs and the architecture of the USB stack on Linux, giving you a good overall picture of how things work. Site: http://www.makelinux.net/ldd3/chp-13-sect-3

4. Linux Documentation input.txt provides very useful information on Linux handling of USB HID and events. Address: https://www.kernel.org/doc/Documentation/input/input.txt

5. freedesktop.org publishes a tool called 'evtest' that can read events to Linux device /dev/eventX. This can be really useful in viewing raw events. The package has only one C file and no lib dependency. So very easy to compile for your target. Site: http://cgit.freedesktop.org/evtest/

6. TI's Wiki has a good overview of how TI's USB stack fits into the Linux USB stack. Site: http://processors.wiki.ti.com/index.php/DM81xx_AM38XX_USB_User_Guide#Linux_USB_Stack_Architecture

January 2, 2014

RJ11 telephone cables

Technical term:
RJ11, RJ14, and RJ25 all use the same physical connector.

RJ11 has two wires.
RJ14 has 4 wires.
RJ25 has 6 wires.

If you want to buy RJ25 connector/cable, search for the term "6p6c" such as on amazon.com

Another theory:
RJ11 has 4 wires: 6p4c
RJ12 has 6 wires: 6p6c

December 18, 2013

The best grep replacement: ag

http://geoff.greer.fm/2011/12/27/the-silver-searcher-better-than-ack/

It's syntax is pretty much the same as ack, but written in optimized C and is noticeably faster.

December 6, 2013

The Telnet Protocol


The Telnet protocol is often thought of as simply providing a facility for remote logins to computer via the Internet. This was its original purpose although it can be used for many other purposes. It is best understood in the context of a user with a simple terminal using the local telnet program (known as the client program) to run a login session on a remote computer where his communications needs are handled by a telnet server program. It should be emphasised that the telnet server can pass on the data it has received from the client to many other types of process including a remote login server. It is described in RFC854 and was first published in 1983.

The Network Virtual Terminal

Communication is established using the TCP/IP protocols and communication is based on a set of facilities known as a Network Virtual Terminal (NVT). At the user or client end the telnet client program is responsible for mapping incoming NVT codes to the actual codes needed to operate the user's display device and is also responsible for mapping user generated keyboard sequences into NVT sequences.
The NVT uses 7 bit codes for characters, the display device, referred to as a printer in the RFC, is only required to display the "standard" printing ASCII characters represented by 7 bit codes and to recognise and process certain control codes. The 7 bit characters are transmitted as 8 bit bytes with most significant bit set to zero. An end-of-line is transmitted as the character sequence CR (carriage return) followed by LF (line feed). If it is desired to transmit an actual carriage return this is transmitted as a carriage return followed by a NUL (all bits zero) character.
NVT ASCII is used by many other Internet protocols.
The following control codes are required to be understood by the Network Virtual Terminal.

Name code Decimal Value Function
NULL NUL 0 No operation
Line Feed LF 10 Moves the printer to the next print line, keeping the same horizontal position.
Carriage Return CR 13 Moves the printer to the left margin of the current line.
The following further control codes are optional but should have the indicated defined effect on the display.

Name code Decimal Value Function
BELL BEL 7 Produces an audible or visible signal (which does NOT move the print head.
Back Space BS 8 Moves the print head one character position towards the left margin. [On a printing devices this mechanism was commonly used to form composite characters by printing two basic characters on top of each other.]
Horizontal Tab HT 9 Moves the printer to the next horizontal tab stop. It remains unspecified how either party determines or establishes where such tab stops are located.
Vertical Tab VT 11 Moves the printer to the next vertical tab stop. It remains unspecified how either party determines or establishes where such tab stops are located.
Form Feed FF 12 Moves the printer to the top of the next page, keeping the same horizontal position. [On visual displays this commonly clears the screen and moves the cursor to the top left corner.]
The NVT keyboard is specified as being capable of generating all 128 ASCII codes by using keys, key combinations or key sequences.

Commands

The telnet protocol also specifies various commands that control the method and various details of the interaction between the client and server. These commands are incorporated within the data stream. The commands are distinguished by the use of various characters with the most significant bit set. Commands are always introduced by a character with the decimal code 255 known as an Interpret as command (IAC) character. The complete set of special characters is

Name Decimal Code Meaning
SE 240 End of subnegotiation parameters.
NOP 241 No operation
DM 242 Data mark. Indicates the position of a Synch event within the data stream. This should always be accompanied by a TCP urgent notification.
BRK 243 Break. Indicates that the "break" or "attention" key was hit.
IP 244 Suspend, interrupt or abort the process to which the NVT is connected.
AO 245 Abort output. Allows the current process to run to completion but do not send its output to the user.
AYT 246 Are you there. Send back to the NVT some visible evidence that the AYT was received.
EC 247 Erase character. The receiver should delete the last preceding undeleted character from the data stream.
EL 248 Erase line. Delete characters from the data stream back to but not including the previous CRLF.
GA 249 Go ahead. Used, under certain circumstances, to tell the other end that it can transmit.
SB 250 Subnegotiation of the indicated option follows.
WILL 251 Indicates the desire to begin performing, or confirmation that you are now performing, the indicated option.
WONT 252 Indicates the refusal to perform, or continue performing, the indicated option.
DO 253 Indicates the request that the other party perform, or confirmation that you are expecting the other party to perform, the indicated option.
DONT 254 Indicates the demand that the other party stop performing, or confirmation that you are no longer expecting the other party to perform, the indicated option.
IAC 255 Interpret as command
There are a variety of options that can be negotiated between a telnet client and server using commands at any stage during the connection.

Common Telnet options:

Decimal code Option Name RFC
0 Transmit Binary 856
1 Echo 857
3 Suppress Go Ahead 858
5 Status 859
6 Timing Mark 860
24 Terminal Type 1091
31 Window Size 1073
32 Terminal Speed 1079
33 Remote Flow Control 1372
34 Linemode 1184
36 Environment Variables 1408
All Telnet options:
Decimal Code Option Name RFC
0 Transmit Binary 856
1 Echo 857
2 Reconnection
3 Suppress Go Ahead 858
4 Approx Message Size Negotiation.
5 Status 859
6 Timing Mark 860
7 Remote Controlled Trans and Echo 563, 726
8 Output Line Width
9 Output Page Size
10 Negotiate About Output Carriage-Return Disposition 652
11 Negotiate About Output Horizontal Tabstops 653
12 NAOHTD, Negotiate About Output Horizontal Tab Disposition 654
13 Negotiate About Output Formfeed Disposition 655
14 Negotiate About Vertical Tabstops 656
15 Negotiate About Output Vertcial Tab Disposition 657
16 Negotiate About Output Linefeed Disposition 658
17 Extended ASCII. 698
18 Logout. 727
19 Byte Macro 735
20 Data Entry Terminal 732,1043
21 SUPDUP 734, 736
22 SUPDUP Output 749
23 Send Location 779
24 Terminal Type 1091
25 End of Record 885
26 TACACS User Identification 927
27 Output Marking 933
28 TTYLOC, Terminal Location Number. 946
29 Telnet 3270 Regime 1041
30 X.3 PAD. 1053
31 NAWS, Negotiate About Window Size. 1073
32 Terminal Speed 1079
33 Remote Flow Control 1372
34 Linemode 1184
35 X Display Location. 1096
36 Environment 1408
37 Authentication 1416, 2941, 2942, 2943,2951
38 Encryption Option 2946
39 New Environment 1572
40 TN3270E 2355
41 XAUTH
42 CHARSET 2066
43 RSP, Telnet Remote Serial Port
44 Com Port Control 2217
45 Telnet Suppress Local Echo
46 Telnet Start TLS
47 KERMIT 2840
48 SEND-URL
49 FORWARD_X
50
-
137
138 TELOPT PRAGMA LOGON
139 TELOPT SSPI LOGON
140 TELOPT PRAGMA HEARTBEAT
141
-
254
255 Extended-Options-List RFC 861
 
Options are agreed by a process of negotiation which results in the client and server having a common view of various extra capabilities that affect the interchange and the operation of applications.
Either end of a telnet dialogue can enable or disable an option either locally or remotely. The initiator sends a 3 byte command of the form

 IAC,<type of operation>,<option>
The response is of the same form.
Operation is one of

Description Decimal Code Action
WILL 251 Sender wants to do something.
WONT 252 Sender doesn't want to do something.
DO 253 Sender wants the other end to do something.
DONT 254 Sender wants the other not to do something.
Associated with each of the these there are various possible responses

Sender Sent Receiver Responds Implication
WILL DO The sender would like to use a certain facility if the receiver can handle it. Option is now in effect
WILL DONT Receiver says it cannot support the option. Option is not in effect.
DO WILL The sender says it can handle traffic from the sender if the sender wishes to use a certain option. Option is now in effect.
DO WONT Receiver says it cannot support the option. Option is not in effect.
WONT DONT Option disabled. DONT is only valid response.
DONT WONT Option disabled. WONT is only valid response.
For example if the sender wants the other end to suppress go-ahead it would send the byte sequence

255(IAC),251(WILL),3

The final byte of the three byte sequence identifies the required action. For some of the negotiable options values need to be communicated once support of the option has been agreed. This is done using sub-option negotiation. Values are communicated via an exchange of value query commands and responses in the following form.

 IAC,SB,<option code number>,1,IAC,SE
and

IAC,SB,<option code>,0,<value>,IAC,SE
For example if the client wishes to identify the terminal type to the server the following exchange might take place

Client   255(IAC),251(WILL),24
Server   255(IAC),253(DO),24
Server   255(IAC),250(SB),24,1,255(IAC),240(SE)
Client   255(IAC),250(SB),24,0,'V','T','2','2','0',255(IAC),240(SE)
The first exchange establishes that terminal type (option number 24) will be handled, the server then enquires of the client what value it wishes to associate with the terminal type. The sequence SB,24,1 implies sub-option negotiation for option type 24, value required (1). The IAC,SE sequence indicates the end of this request. The repsonse IAC,SB,24,0,'V'... implies sub-option negotiation for option type 24, value supplied (0), the IAC,SE sequence indicates the end of the response (and the supplied value). The encoding of the value is specific to the option but a sequence of characters, as shown above, is common.                          

Source: http://pcmicro.com/netfoss/telnet.html