/****************************************************************************************
* CANopenSocket CANopenCGI.c hacking
* 说明:
* 分析一下CANopenSocket中的CANopenCGI部分是怎么工作的。
*
* 2017-3-23 深圳 南山平山村 曾剑锋
***************************************************************************************/ /*
* Client socket command interface (Apache CGI) for CANopenSocket.
*
* @file CANopenCGI.c
* @author Janez Paternoster
* @copyright 2016 Janez Paternoster
*
* This file is part of CANopenNode, an opensource CANopen Stack.
* Project home page is <https://github.com/CANopenNode/CANopenNode>.
* For more information on CANopen see <http://www.can-cia.org/>.
*
* CANopenNode is free and open source software: you can redistribute
* it and/or modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
#include <fnmatch.h>
#include <sys/un.h>
#include <sys/socket.h> #ifndef BUF_SIZE
#define BUF_SIZE 100000
#endif /* Helper functions */
static void errExitErrno(char* msg) {
printf("%s: %s\n", msg, strerror(errno));
exit(EXIT_FAILURE);
} static void errExit(char* msg) {
printf("%s\n", msg);
exit(EXIT_FAILURE);
} /**
* 字符串拷贝并转换成大写
*/
static void strcpyToUpper(char *dest, const char *src) {
char in; do {
in = *(src++);
*(dest++) = toupper(in);
} while(in != );
} /**
* 字符串转换成大写
*/
static void strToUpper(char *str) {
char c; do {
c = *(str);
*(str++) = toupper(c);
} while(c != );
} /**
* 字符串转换成小写
*/
static void strToLower(char *str) {
char c; do {
c = *(str);
*(str++) = tolower(c);
} while(c != );
} /* Decode hex string 'str' of length 'len' and return numerical value.
* In case of error in string, set 'err' to 1. */
/**
* 将十六进制的字符串转成数字
*/
static unsigned int hex2dec(const char *str, int len, int *err){
unsigned int val = ;
int i; for(i=; i<len; i++) {
char c = str[i];
if(c >= '' && c <= '') {
c = c - '';
} else if (c >= 'A' && c <= 'F') {
c = c - ('A' - );
}
else {
*err = ;
return ;
}
val = val << | c;
}
return val;
} static void sendCommand(int fd, int sequence, char* command); static void printUsage(void) {
printf(
"Usage: canopen.cgi?wnniiiissdd=xxxx[&rnniiiissdd=]\n"
" - w - One digit - 'W'rite or 'R'ead.\n"
" - nn - Two hex digits of node ID.\n"
" - iiii - Four hex digits of Object Dictionary Index.\n"
" - ss - Two hex digits of Object Dictionary Subindex.\n"
" - dd - One to three digits of data type.\n"
" - xxxx - Value to be written.\n"
"\n"
"Datatypes:\n"
" - b - Boolean.\n"
" - u8, u16, u32, u64 - Unsigned integers.\n"
" - i8, i16, i32, i64 - Signed integers.\n"
" - r32, r64 - Real numbers.\n"
" - t, td - Time of day, time difference.\n"
" - vs - Visible string (between double quotes).\n"
" - os, us, d - Octet string, unicode string, domain."
);
} /******************************************************************************/
int main (int argc, char *argv[], char *env[]) {
char socketPath[] = {}; /* Name of the local domain socket. */ FILE *fp;
int fdSocket;
struct sockaddr_un addr;
char *queryString;
int queryStringAllocated = ; /* whitelist and blacklist are arrays of null separated strings, which
* contains patterns for comparision with commands from query string. */
char *whitelist;
char *blacklist;
int whitelistLen;
int blacklistLen; /* Print mime */
/**
* 输出http协议的头
*/
printf("Content-type:text/plain\n\n"); /* Get program options from configuration file */
/**
* 处理配置文件
*/
fp = fopen("canopen.conf", "r");
if(fp == NULL) {
errExitErrno("Can't open configuration file");
}
else {
const char spaceDelim[] = " \t\n\r\f\v";
char buf[];
int wlSize = ; /* byte length */
int blSize = ;
int wlDataSize = ;
int blDataSize = ; whitelist = (char *) malloc(wlSize);
blacklist = (char *) malloc(blSize);;
// 最开始wlDataSize长度都是0,随着allow检测到的配置越来越多,长度会越来越长
whitelistLen = ; /* number of tokens in list */
blacklistLen = ;
if(whitelist == NULL || blacklist == NULL) {
errExitErrno("Whitelist or Blacklist can't be allocated.");
} // 每次读取一行
while(fgets(buf, sizeof(buf), fp) != NULL) {
char *token;
token = strtok(buf, spaceDelim); if(token == NULL) { }
/**
* 获取socketPath配置
*/
else if(strcasecmp(token, "socketPath") == ) {
if(strlen(socketPath) != ) {
errExit("Duplicate 'socketPath' in canopen.conf.");
}
strncpy(socketPath, strtok(NULL, spaceDelim), sizeof(socketPath));
socketPath[sizeof(socketPath)-] = ;
}
else if(strcasecmp(token, "allow") == ) {
// 保存上一次的wlDataSize长度,随着allow检测到的配置越来越多,长度会越来越长
int prevDataSize = wlDataSize; // 获取value
token = strtok(NULL, spaceDelim);
// 计算value长度并+1,最后一个字节用于存放字符串结束符,这个长度叠加到wlDataSize中
wlDataSize += (strlen(token) + );
// 长度大于预设字符串长度,双倍扩容并重新分配,不过从这里开看最大也就是双倍的扩容长度
while(wlDataSize > wlSize) {
wlSize *= ;
whitelist = (char *) realloc(whitelist, wlSize);
if(whitelist == NULL) {
errExitErrno("Whitelist can't be allocated.");
}
}
// 拷贝当前的匹配数据到whitelist中
strcpyToUpper(&whitelist[prevDataSize], token);
whitelistLen ++;
}
/**
* 类是于白名单
*/
else if(strcasecmp(token, "deny") == ) {
int prevDataSize = blDataSize; token = strtok(NULL, spaceDelim);
blDataSize += (strlen(token) + );
while(blDataSize > blSize) {
blSize *= ;
blacklist = (char *) realloc(blacklist, blSize);
if(blacklist == NULL) {
errExitErrno("Blacklist can't be allocated.");
}
}
strcpyToUpper(&blacklist[prevDataSize], token);
blacklistLen ++;
}
}
} fclose(fp); /* Create and connect client socket */
/**
* 创建本地socket
*/
fdSocket = socket(AF_UNIX, SOCK_STREAM, );
if(fdSocket == -) {
errExitErrno("Socket creation failed");
} /**
* 配置本地socket
*/
memset(&addr, , sizeof(struct sockaddr_un));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, socketPath, sizeof(addr.sun_path) - ); /**
* 连接本地socket
*/
if(connect(fdSocket, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -) {
errExitErrno("Socket connection failed");
} /* get query string */
/**
* 获取网络请求数据
*/
queryString = getenv("QUERY_STRING"); /* HTTP GET method. */
if(queryString != NULL && strlen(queryString) == ) {
queryString = malloc(BUF_SIZE);
if(queryString == NULL) {
errExitErrno("queryString can't be allocated.");
}
queryStringAllocated = ;
fgets(queryString, BUF_SIZE, stdin); /* HTTP POST method. */
}
if(queryString == NULL && argc >= ) {
queryString = argv[]; /* If no query string, try first argument. */
} /* get commands from query string */
/**
* 解析网络请求数据
*/
if(queryString != NULL && strlen(queryString) > ) {
char *command;
int sequence = ; /* put whole query string to upper case */
/**
* 将请求数据转为大写的格式
*/
strToUpper(queryString); command = strtok(queryString, "&");
while(command != NULL) {
int i;
int offset;
int passed = ; /* Test whitelist and blacklist */
/**
* 一个一个偏移着找
*/
offset = ;
for(i=; i<whitelistLen; i++) {
char *patern = &whitelist[offset];
if(fnmatch(patern, command, ) == ) {
passed = ;
break;
}
offset += strlen(patern) + ;
}
/**
* 检查黑名单
*/
if(passed == ) {
offset = ;
for(i=; i<blacklistLen; i++) {
char *patern = &blacklist[offset];
if(fnmatch(patern, command, ) == ) {
passed = -; /* not allowed */
break;
}
offset += strlen(patern) + ;
}
} /* Send command or error message */
if(strlen(command) < ) {
printf("? %s [%d] ERROR: 101 - Syntax error in command.\n", command, sequence);
}
else if(passed == ) {
sendCommand(fdSocket, sequence, command);
}
else {
printf("%c %c%c%c%c%c%c%c%c [%d] ERROR: 100 - Access restriction, command %s.\n",
command[], command[], command[], command[], command[],
command[], command[], command[], command[],
sequence, (passed==)?"not on whitelist":" on blacklist");
} command = strtok(NULL, "&");
sequence ++;
}
}
else {
printUsage();
} close(fdSocket);
free(whitelist); // 释放白名单
free(blacklist); // 释放黑名单
if(queryStringAllocated == ) {
free(queryString);
} exit(EXIT_SUCCESS);
} static void sendCommand(int fd, int sequence, char* command) {
int i, err;
char comm;
unsigned int nodeId, idx, sidx;
char dataType[];
char *value = ""; char buf[BUF_SIZE]; /* Parse command. It is at least 8 characters long. */
/**
* 解析命令
*/
err = ; comm = command[];
if(comm != 'R' && comm != 'W') {
err = ;
} nodeId = hex2dec(&command[], , &err);
if(nodeId < || nodeId > ) {
err = ;
} idx = hex2dec(&command[], , &err);
sidx = hex2dec(&command[], , &err); for(i=; i<sizeof(dataType); i++) {
char c = command[+i]; if(c == '=' || c == ) {
dataType[i] = ;
if(c == '=') {
value = &command[+i];
}
break;
}
dataType[i] = c;
}
if(i > ) {
err = ;
dataType[] = ;
}
if(strlen(value) > (sizeof(buf) - )) {
err = ;
} /* Write command according to CiA309-3. */
/**
* 命令转换,转换成canopend能接收的命令格式
*/
if(err == ) {
size_t wlen, rlen; strToLower(dataType); wlen = sprintf(buf, "[%d] 0x%02X %c 0x%04X 0x%02X %s %s\n",
sequence, nodeId, tolower(comm), idx, sidx, dataType, value); if (write(fd, buf, wlen) != wlen) {
errExit("Socket write failed");
} rlen = read(fd, buf, sizeof(buf)); if(rlen == -) {
errExit("Socket read failed");
} printf("%c %02X%04X%02X %s",
comm, nodeId, idx, sidx, buf);
}
else {
printf("? %s [%d] ERROR: 101 - Syntax error in command.\n",
command, sequence);
}
}

最新文章

  1. HBase的Write Ahead Log (WAL) —— API与基本概念
  2. WebStorm 9 配置 Live Edit 功能与浏览器实现同步
  3. 使用 SQL 命令 OPTIMIZE TABLE 释放表空间
  4. ajaxfileupload asp.net 的简单使用
  5. 关于查询扩展版ESI高被引论文的说明
  6. linux知识点总结与随笔(关注linux爱好者公众号的一些笔记)
  7. 《HeadFirst设计模式》读后感——对学习设计模式的一些想法
  8. Python3.5入门学习记录-函数
  9. visual assist常用快捷键
  10. poj3077---进位
  11. mvc导航配置
  12. Fourinone 作者博客 -集群复制
  13. Python之MRO及其C3算法
  14. 【HOSTS相关】前端提供测试模板地址
  15. Deep learning:一(基础知识_1)
  16. ajax的xmlHttpRequest异步请求和Springmvc的sendRedirect失效问题
  17. pointer-events: none 的两个应用场景
  18. p1010幂次方---(分治)
  19. opencv学习笔记(四)
  20. BZOJ 3498: PA2009 Cakes 一类经典的三元环计数问题

热门文章

  1. Web前端开发的基本要求和认识
  2. PCIE phy和控制器
  3. 常用模块----time&amp;random&amp;hushlib&amp;os
  4. word导出失败问题
  5. LeetCode——same-tree
  6. C#反射第一天
  7. js替换字符串中的数字或非数字
  8. Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named &#39;company&#39; in &#39;class java.lang.String&#39;
  9. hadoop 指定 key value分隔符
  10. Python之爬虫总结