Merge remote-tracking branch 'upstream/v2.0' into openkylin/yangtze

This commit is contained in:
shaozhimin 2022-10-20 19:35:59 +08:00
commit 8a8a4da1ba
33 changed files with 1499 additions and 324 deletions

26
.gitignore vendored Normal file
View File

@ -0,0 +1,26 @@
.vscode
build/
/lib/
bin/
obj-x86_64-linux-gnu/
debian/tmp/
debian/files/
debian/libkysdk-disk/
debian/libkysdk-disk-dev/
debian/libkysdk-filesystem/
debian/libkysdk-filesystem-dev/
debian/libkysdk-hardware/
debian/libkysdk-hardware-dev/
debian/libkysdk-package/
debian/libkysdk-package-dev/
debian/libkysdk-proc/
debian/libkysdk-proc-dev/
debian/libkysdk-sysinfo/
debian/libkysdk-sysinfo-dev/
debian/libkysdk-system/
debian/libkysdk-system-dev/
debian/libkysdk-systime/
debian/libkysdk-systime-dev/
debian/libkysdk*.substvars
debian/libkysdk*.debhelper
debian/.debhelper

18
debian/changelog vendored
View File

@ -1,3 +1,21 @@
libkysdk-system (2.0.0.0-ok2) yangtze; urgency=medium
*Bug号
*需求号:
*其他修改:[新增] 新增获取多个端口状态及防火墙状态接口
[新增] 新增获取磁盘转速接口
[新增] 新增获取地理位置信息接口
[新增] 获取本地打印机列表/获取可用打印机列表
[新增] 设置打印参数
[新增] 下载网络文件到本地
[新增] 打印本地文件
[新增] 获取打印机的状态
[新增] 获取打印任务的状态
[新增] 清除某个打印机的所有打印队列
[新增] 从url中获取文件名的接口
-- szm-min <shaozhimin@kylinos.cn> Thu, 20 Oct 2022 19:22:40 +0800
libkysdk-system (2.0.0.0-ok2) yangtze; urgency=medium
*Bug号

43
debian/control vendored
View File

@ -20,6 +20,8 @@ Build-Depends: debhelper-compat (= 12),
libopencv-dev,
libarchive-dev,
libtesseract-dev,
libcups2-dev,
libcurl4-openssl-dev,
libxrandr-dev
Standards-Version: 4.4.1
Homepage: http://gitlab2.kylin.com/kysdk/kysdk-system
@ -40,6 +42,7 @@ Depends: ${shlibs:Depends},
systemd,
libglib2.0-0,
libkysdk-systemcommon,
libkysdk-location,
libkysdk-net,
libkysdk-realtime
Multi-Arch: same
@ -60,6 +63,7 @@ Depends: ${shlibs:Depends},
libkysdk-hardware-dev,
libkysdk-package-dev,
libkysdk-powermanagement-dev,
libkysdk-location-dev,
libkysdk-net-dev,
libkysdk-realtime-dev
Multi-Arch: same
@ -179,7 +183,9 @@ Depends: ${shlibs:Depends},
libkysdk-log(>=1.2.0),
libkysdk-config(>=1.2.0),
systemd,
libkysdk-systemcommon
libkysdk-systemcommon,
libcups2-dev,
libcurl4-openssl-dev,
Multi-Arch: same
Description: 硬件信息获取库
@ -192,6 +198,8 @@ Depends: ${shlibs:Depends},
libkysdk-log-dev(>=1.2.0),
libkysdk-config-dev(>=1.2.0),
libsystemd-dev
libsystemd-dev,
libcups2-dev
Multi-Arch: same
Description: 硬件信息获取库 - 开发库
@ -280,23 +288,24 @@ Depends: ${shlibs:Depends},
Multi-Arch: same
Description: kysdk-system层公用数据包
# Package: libkysdk-location
# Architecture: any
# Section: utils
# Depends: ${shlibs:Depends},
# ${misc:Depends},
# libkysdk-systemcommon,
# Multi-Arch: same
# Description: 地理位置库
Package: libkysdk-location
Architecture: any
Section: utils
Depends: ${shlibs:Depends},
${misc:Depends},
libkysdk-systemcommon,
libglib2.0-0
Multi-Arch: same
Description: 地理位置库
# Package: libkysdk-location-dev
# Architecture: any
# Section: utils
# Depends: ${shlibs:Depends},
# ${misc:Depends},
# libkysdk-location
# Multi-Arch: same
# Description: 地理位置库 - 开发库
Package: libkysdk-location-dev
Architecture: any
Section: utils
Depends: ${shlibs:Depends},
${misc:Depends},
libkysdk-location
Multi-Arch: same
Description: 地理位置库 - 开发库
Package: libkysdk-net
Architecture: any

View File

@ -1,5 +1,6 @@
usr/include/kysdk/kysdk-system/libkync.h
usr/include/kysdk/kysdk-system/libkycpu.h
usr/include/kysdk/kysdk-system/libkyprinter.h
usr/include/kysdk/kysdk-system/libkybios.h
usr/include/kysdk/kysdk-system/libkyboard.h
usr/include/kysdk/kysdk-system/libkyusb.h

View File

@ -0,0 +1,2 @@
usr/include/kysdk/kysdk-system/libkylocation.h
development-files/kysdk-location.pc usr/share/pkgconfig/

View File

@ -0,0 +1,4 @@
usr/lib/kysdk/kysdk-system/libkylocation.so*
src/location/location.py usr/bin
src/location/dbus_location.conf etc/dbus-1/system.d/
src/location/dbus_location.service lib/systemd/system/

View File

@ -1,6 +1,6 @@
Name: libkysdk-location
Description: kysdk system layer location
Requires:
Requires:glib-2.0
Version: 2.0.0
Libs: -L/usr/lib/kysdk/kysdk-system/ -lkylocation -Wl,-rpath=/usr/lib/kysdk/kysdk-system/
Cflags: -I/usr/include/kysdk/kysdk-system/

View File

@ -4,6 +4,14 @@ add_library(kyhw SHARED ${SOURCESCODE})
set_target_properties(kyhw PROPERTIES VERSION 2.0.0 SOVERSION 1)
add_executable(kync-test test/kync-test.c)
add_executable(kycpu-test test/kycpu-test.c)
add_executable(kyprinterlist-test test/kyprinterlist-test.c)
add_executable(kyprinterprint-test test/kyprinterprint-test.c)
#
target_link_libraries(kyhw kylog kyconf pthread systemd cups curl)
target_link_libraries(kync-test kyhw)
target_link_libraries(kycpu-test kyhw)
target_link_libraries(kyprinterprint-test kyhw)
target_link_libraries(kyprinterlist-test kyhw)
add_executable(kyusb-test test/kyusb-test.c)
add_executable(kybios-test test/kybios-test.c)
add_executable(kyboard-test test/kyboard-test.c)
@ -23,6 +31,9 @@ install(FILES libkync.h
install(FILES libkycpu.h
DESTINATION include/kysdk/kysdk-system)
install(FILES libkyprinter.h
DESTINATION include/kysdk/kysdk-system)
install(FILES libkybios.h
DESTINATION include/kysdk/kysdk-system)

View File

@ -318,6 +318,8 @@ char* kdk_nc_get_private_ipv6(const char *nc)
int kdk_nc_is_wireless(const char *nc)
{
if (!nc)
return -1;
char buffer[2 * IFNAMSIZ + 1];
int fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd < 0)
@ -329,6 +331,8 @@ int kdk_nc_is_wireless(const char *nc)
int kdk_nc_get_vendor_and_product(const char *nc, char *vendor, char *product)
{
if (!nc)
return -1;
char filename[64] = "0";
sprintf(filename, "/sys/class/net/%s/device", nc);
if (0 != access(filename, F_OK))

511
src/hardware/libkyprinter.c Normal file
View File

@ -0,0 +1,511 @@
#include "libkyprinter.h"
#include <errno.h>
#include <libkylog.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <syslog.h>
#include <cups/cups.h>
#include <cups/adminutil.h>
#include <cups/ipp.h>
#include <cups/ppd.h>
#include <curl/curl.h>
#include <stdbool.h>
#include <stdlib.h>
#define _IPP_PRIVATE_STRUCTURES 1
cups_option_t *cups_options; // cups设置
int num_options; // cups设置
char **kdk_printer_get_list()
{
printf("[%s] Start\n", __FUNCTION__);
cups_dest_t *dests = NULL;
int num_dests = 0;
int i = 0;
char **printers = NULL;
num_dests = cupsGetDests(&dests);
if (num_dests == 0 &&
(cupsLastError() == IPP_STATUS_ERROR_BAD_REQUEST ||
cupsLastError() == IPP_STATUS_ERROR_VERSION_NOT_SUPPORTED))
{
#ifdef PRT_DEBUG
_cupsLangPrintf(stderr, "Printer: Error - add '/version=1.1' to server name.");
#endif
return NULL;
}
for (i = 0; i < num_dests; i++)
{
printf("[%s] printer name is %s \n", __FUNCTION__, dests[i].name);
char **tmp = realloc(printers, sizeof(char *) * i);
printers = tmp;
printers[i] = malloc(sizeof(char) * (strlen(dests[i].name) + 1));
strcpy(printers[i], dests[i].name);
}
char **tmp = realloc(printers, sizeof(char *) * (i + 1));
printers = tmp;
printers[i] = NULL;
cupsFreeDests(num_dests, dests);
return printers;
}
char **kdk_printer_get_available_list()
{
printf("[%s] Start\n", __FUNCTION__);
cups_dest_t *dests = NULL;
int num_dests = 0;
int i = 0, j = 0;
char **printers = NULL;
num_dests = cupsGetDests(&dests);
if (num_dests == 0 &&
(cupsLastError() == IPP_STATUS_ERROR_BAD_REQUEST ||
cupsLastError() == IPP_STATUS_ERROR_VERSION_NOT_SUPPORTED))
{
#ifdef PRT_DEBUG
_cupsLangPrintf(stderr, "Printer: Error - add '/version=1.1' to server name.");
#endif
return NULL;
}
for (i = 0; i < num_dests; i++)
{
if (kdk_printer_get_status(dests[i].name) == CUPS_PRINTER_STATE_IDLE)
{
printf("[%s] printer name is %s \n", __FUNCTION__, dests[i].name);
char **tmp = realloc(printers, sizeof(char *) * j);
printers = tmp;
printers[j] = malloc(sizeof(char) * (strlen(dests[i].name) + 1));
strcpy(printers[j], dests[i].name);
//
j++;
}
}
char **tmp = realloc(printers, sizeof(char *) * (j + 1));
printers = tmp;
printers[j] = NULL;
cupsFreeDests(num_dests, dests);
return printers;
}
int kdk_printer_remove_options()
{
printf("[%s] Start\n", __FUNCTION__);
if (num_options != 0 && cups_options != NULL)
{
cupsFreeOptions(num_options, cups_options);
num_options = 0;
cups_options = NULL;
}
printf("[%s] num_options = %d\n", __FUNCTION__, num_options);
return 0;
}
void kdk_printer_set_options(int number_up,
const char *media,
const char *number_up_layout, const char *sides)
{
printf("[%s] Start\n", __FUNCTION__);
kdk_printer_remove_options();
cups_options = NULL;
num_options = 0;
char NumberUp[2] = {0};
snprintf(NumberUp, 2, "%d", number_up);
/* cups options */
num_options = cupsAddOption("number-up", NumberUp, num_options, &cups_options);
num_options = cupsAddOption("media", media, num_options, &cups_options);
num_options = cupsAddOption("number-up-layout", number_up_layout, num_options, &cups_options);
num_options = cupsAddOption("sides", sides, num_options, &cups_options);
}
int kdk_printer_print_local_file(const char *printername, char *filepath)
{
printf("[%s] Start\n", __FUNCTION__);
printf("[%s] printer_name: %s, file_path: %s\n", __FUNCTION__,
printername,
filepath);
int jobid = 0;
// stop状态禁止打印
if (kdk_printer_get_status(printername) != CUPS_PRINTER_STATE_STOPPED)
{
jobid = cupsPrintFile(printername, filepath, "Print report", num_options, cups_options);
//注意:这里没有设置格式的话会直接用默认格式,一般默认格式是单页打印
// printf("[%s] num_options = %d,name = %s,value = %s",
// __FUNCTION__,num_options,cups_options->name,cups_options->value);
}
return jobid;
}
int kdk_printer_cancel_all_jobs(const char *printername)
{
printf("[%s] Start\n", __FUNCTION__);
int ret = cupsCancelJob(printername, CUPS_JOBID_ALL); // 1=success 0=fail
if (ret == 0)
{
printf(LOG_ERR, "%s ,job_id = CUPS_JOBID_ALL, find err = %s ", __FUNCTION__, cupsLastErrorString());
return -1;
}
return 0;
}
static int /* O - 1 on match, 0 on no match */
match_list(const char *list, /* I - List of names */
const char *name) /* I - Name to find */
{
const char *nameptr; /* Pointer into name */
/*
* An empty list always matches...
*/
if (!list || !*list)
return (1);
if (!name)
return (0);
while (*list)
{
/*
* Skip leading whitespace and commas...
*/
while (isspace(*list & 255) || *list == ',')
list++;
if (!*list)
break;
/*
* Compare names...
*/
for (nameptr = name;
*nameptr && *list && tolower(*nameptr & 255) == tolower(*list & 255);
nameptr++, list++)
;
if (!*nameptr && (!*list || *list == ',' || isspace(*list & 255)))
return (1);
while (*list && !isspace(*list & 255) && *list != ',')
list++;
}
return (0);
}
static int /* O - 0 on success, 1 on fail */
_show_printer_state(const char *printers /* I - Destinations */
// char* buf, /* I - Number of user-defined dests */
) /* I - User-defined destinations */
{
int i; /* Looping var */
ipp_t *request, /* IPP Request */
*response; /* IPP Response */
ipp_attribute_t *attr; /* Current attribute */
time_t ptime; /* Printer state time */
const char *printer, /* Printer name */
*device; /* Printer device URI */
ipp_pstate_t pstate;
int state_code = 0;
static const char *pattrs[] = /* Attributes we need for printers... */
{
"printer-name",
"printer-state"};
#ifdef PRT_DEBUG
printf(("show_devices(printers=\"%s\")\n", printers));
#endif
if (printers != NULL && !strcmp(printers, "all"))
printers = NULL;
/*
* Build a CUPS_GET_PRINTERS request, which requires the following
* attributes:
*
* attributes-charset
* attributes-natural-language
* requested-attributes
* requesting-user-name
*/
request = ippNewRequest(CUPS_GET_PRINTERS);
ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
"requested-attributes", sizeof(pattrs) / sizeof(pattrs[0]),
NULL, pattrs);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
NULL, cupsUser());
/*
* Do the request and get back a response...
*/
response = cupsDoRequest(CUPS_HTTP_DEFAULT, request, "/");
if (cupsLastError() == IPP_STATUS_ERROR_BAD_REQUEST ||
cupsLastError() == IPP_STATUS_ERROR_VERSION_NOT_SUPPORTED)
{
#ifdef PRT_DEBUG
_cupsLangPrintf(stderr,
"%s: Error - add '/version=1.1' to server name.",
"lpstat");
#endif
ippDelete(response);
return (1);
}
else if (cupsLastError() > IPP_STATUS_OK_CONFLICTING)
{
#ifdef PRT_DEBUG
_cupsLangPrintf(stderr, "lpstat: %s", cupsLastErrorString());
#endif
ippDelete(response);
return (1);
}
if (response)
{
/*
* Loop through the printers returned in the list and display
* their devices...
*/
attr = ippFirstAttribute(response);
for (; attr != NULL; attr = ippNextAttribute(response))
{
/*
* Skip leading attributes until we hit a job...
*/
while (attr != NULL && ippGetGroupTag(attr) != IPP_TAG_PRINTER)
attr = ippNextAttribute(response);
if (attr == NULL)
break;
/*
* Pull the needed attributes from this job...
*/
printer = NULL;
pstate = IPP_PRINTER_IDLE;
while (attr != NULL && ippGetGroupTag(attr) == IPP_TAG_PRINTER)
{
const char *attr_name = ippGetName(attr);
ipp_tag_t value_tag = ippGetValueTag(attr);
if (!strcmp(attr_name, "printer-name") &&
value_tag == IPP_TAG_NAME)
printer = ippGetString(attr, 0, NULL);
else if (!strcmp(attr_name, "printer-state") &&
value_tag == IPP_TAG_ENUM)
{
pstate = (ipp_pstate_t)ippGetInteger(attr, 0);
// printf("statecode: %d\n",ippGetInteger(attr,0));
}
attr = ippNextAttribute(response);
}
/*
* See if we have everything needed...
*/
if (printer == NULL)
{
if (attr == NULL)
break;
else
continue;
}
if (match_list(printers, printer))
{
switch (pstate)
{
case IPP_PRINTER_IDLE:
state_code = CUPS_PRINTER_STATE_IDLE;
// snprintf(buf,buf_len,PRINTER_STATE_IDLE);
break;
case IPP_PRINTER_PROCESSING:
state_code = CUPS_PRINTER_STATE_PROCESSING;
// snprintf(buf,buf_len,PRINTER_STATE_PROCESSING);
break;
case IPP_PRINTER_STOPPED:
state_code = CUPS_PRINTER_STATE_STOPPED;
// snprintf(buf,buf_len,PRINTER_STATE_STOPPED);
break;
case IPP_PRINTER_BUSY:
state_code = CUPS_PRINTER_STATE_PROCESSING;
// snprintf(buf,buf_len,PRINTER_STATE_PROCESSING);
break;
default:
state_code = CUPS_PRINTER_STATE_STOPPED;
// snprintf(buf,buf_len,PRINTER_STATE_STOPPED);
break;
}
}
if (attr == NULL)
break;
}
ippDelete(response);
}
return state_code;
}
int kdk_printer_get_status(const char *printername)
{
printf("[%s] Start\n", __FUNCTION__);
http_t *http; /* Connection to server */
int ret;
if ((http = httpConnectEncrypt(cupsServer(), ippPort(),
cupsEncryption())) != NULL)
{
httpClose(http);
}
else
{
return -2;
}
return _show_printer_state(printername);
}
size_t processdata(void *buffer, size_t size, size_t nmemb, void *user_p)
{
return nmemb;
}
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
//获取url内的文件名
void kdk_printer_get_filename(const char *url, char *filename)
{
printf("[%s] Start\n", __FUNCTION__);
int len = strlen(url);
int i;
for (i = (len - 1); i >= 0; i--)
{
if ((url[i] == '\\') || (url[i] == '/'))
{
break;
}
}
strcpy(filename, &url[i + 1]);
return;
}
//检查url是否存在
bool check_url(char *url)
{
printf("[%s] Start\n", __FUNCTION__);
// 获得一个CURL会话进行网络操作
CURL *handle = curl_easy_init();
if (NULL != handle && NULL != url)
{
// 设置本次会话的参数
// URL就是我们要验证的网址
curl_easy_setopt(handle, CURLOPT_URL, url);
// 设置连接超时
curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, 5);
// 只是获取HTML的header
curl_easy_setopt(handle, CURLOPT_HEADER, true);
curl_easy_setopt(handle, CURLOPT_NOBODY, true);
// 设置最大重定向数为0不允许页面重定向
curl_easy_setopt(handle, CURLOPT_MAXREDIRS, 0);
// 设置一个空的写入函数,屏蔽屏幕输出
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, &processdata);
// 以上面设置的参数执行这个会话,向服务器发起请求
curl_easy_perform(handle);
// 获取HTTP的状态代码
// 根据代码判断网址是否有效
int retcode = 0;
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &retcode);
bool res = false;
// 如果HTTP反应代码为200表示网址有效
if (200 == retcode)
{
res = true;
}
// 执行会话的清理工作
curl_easy_cleanup(handle);
return res;
}
else // 无法验证
{
return false;
}
}
//下载url到文件
int download_file(char *url, const char *savefile)
{
printf("[%s] Start\n", __FUNCTION__);
CURL *curl;
FILE *fp;
CURLcode res;
printf("[%s] url = %s \n", __FUNCTION__, url);
printf("[%s] savefile = %s \n", __FUNCTION__, savefile);
curl = curl_easy_init();
if (curl)
{
fp = fopen(savefile, "wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L); // timeout for the connect phase
/* abort if slower than 1 bytes/sec during 6 seconds */
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 6);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
return res;
}
int kdk_printer_print_download_remote_file(const char *url, const char *filepath)
{
printf("[%s] Start\n", __FUNCTION__);
int res = -1;
bool available = check_url(url);
if (available)
{
res = download_file(url, filepath);
}
else
{
printf("%s seems to be unavailable.\n", url);
}
printf("res = %d.\n", res);
return res;
}
int kdk_printer_get_job_status(const char *printername, int jobid)
{
printf("[%s] Start\n", __FUNCTION__);
cups_job_t *jobs = NULL;
int i;
int number_jobs;
int ret;
number_jobs = cupsGetJobs(&jobs, printername, 1, CUPS_WHICHJOBS_ALL);
ipp_jstate_t state = 0;
for (i = 0; i < number_jobs; i++)
{
if (jobs[i].id == jobid)
{
state = jobs[i].state;
printf("[%s] job state is %d\n", __FUNCTION__, jobs[i].state);
break;
}
}
cupsFreeJobs(number_jobs, jobs);
return state;
}

258
src/hardware/libkyprinter.h Normal file
View File

@ -0,0 +1,258 @@
#ifndef KDK_SYSTEM_HW_NWCARD_H__
#define KDK_SYSTEM_HW_NWCARD_H__
//打印机状态
#define CUPS_PRINTER_STATE_BUSY 6 //"Busy"
#define CUPS_PRINTER_STATE_STOPPED 4 //"Stop"
#define CUPS_PRINTER_STATE_IDLE 2 //"Idle"
#define CUPS_PRINTER_STATE_PROCESSING 3 //"Processing"
//打印任务状态
#define IPP_JOB_PENDING 3 //挂起等待打印
#define IPP_JOB_HELD 4 //等待打印
#define IPP_JOB_PROCESSING 5 //打印中
#define IPP_JOB_STOPPED 6 //停止
#define IPP_JOB_CANCELED 7 //取消
#define IPP_JOB_ABORTED 8 //由于错误跳过该打印任务
#define IPP_JOB_COMPLETED 9 //正常完成
//下载状态
// typedef enum {
// CURLE_OK = 0,
// CURLE_UNSUPPORTED_PROTOCOL, /* 1 */
// CURLE_FAILED_INIT, /* 2 */
// CURLE_URL_MALFORMAT, /* 3 */
// CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for
// 7.17.0, reused in April 2011 for 7.21.5] */
// CURLE_COULDNT_RESOLVE_PROXY, /* 5 */
// CURLE_COULDNT_RESOLVE_HOST, /* 6 */
// CURLE_COULDNT_CONNECT, /* 7 */
// CURLE_WEIRD_SERVER_REPLY, /* 8 */
// CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server
// due to lack of access - when login fails
// this is not returned. */
// CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for
// 7.15.4, reused in Dec 2011 for 7.24.0]*/
// CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */
// CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server
// [was obsoleted in August 2007 for 7.17.0,
// reused in Dec 2011 for 7.24.0]*/
// CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */
// CURLE_FTP_WEIRD_227_FORMAT, /* 14 */
// CURLE_FTP_CANT_GET_HOST, /* 15 */
// CURLE_HTTP2, /* 16 - A problem in the http2 framing layer.
// [was obsoleted in August 2007 for 7.17.0,
// reused in July 2014 for 7.38.0] */
// CURLE_FTP_COULDNT_SET_TYPE, /* 17 */
// CURLE_PARTIAL_FILE, /* 18 */
// CURLE_FTP_COULDNT_RETR_FILE, /* 19 */
// CURLE_OBSOLETE20, /* 20 - NOT USED */
// CURLE_QUOTE_ERROR, /* 21 - quote command failure */
// CURLE_HTTP_RETURNED_ERROR, /* 22 */
// CURLE_WRITE_ERROR, /* 23 */
// CURLE_OBSOLETE24, /* 24 - NOT USED */
// CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */
// CURLE_READ_ERROR, /* 26 - couldn't open/read from file */
// CURLE_OUT_OF_MEMORY, /* 27 */
// /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error
// instead of a memory allocation error if CURL_DOES_CONVERSIONS
// is defined
// */
// CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */
// CURLE_OBSOLETE29, /* 29 - NOT USED */
// CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */
// CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */
// CURLE_OBSOLETE32, /* 32 - NOT USED */
// CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */
// CURLE_HTTP_POST_ERROR, /* 34 */
// CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */
// CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */
// CURLE_FILE_COULDNT_READ_FILE, /* 37 */
// CURLE_LDAP_CANNOT_BIND, /* 38 */
// CURLE_LDAP_SEARCH_FAILED, /* 39 */
// CURLE_OBSOLETE40, /* 40 - NOT USED */
// CURLE_FUNCTION_NOT_FOUND, /* 41 - NOT USED starting with 7.53.0 */
// CURLE_ABORTED_BY_CALLBACK, /* 42 */
// CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */
// CURLE_OBSOLETE44, /* 44 - NOT USED */
// CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */
// CURLE_OBSOLETE46, /* 46 - NOT USED */
// CURLE_TOO_MANY_REDIRECTS, /* 47 - catch endless re-direct loops */
// CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */
// CURLE_TELNET_OPTION_SYNTAX, /* 49 - Malformed telnet option */
// CURLE_OBSOLETE50, /* 50 - NOT USED */
// CURLE_OBSOLETE51, /* 51 - NOT USED */
// CURLE_GOT_NOTHING, /* 52 - when this is a specific error */
// CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */
// CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as
// default */
// CURLE_SEND_ERROR, /* 55 - failed sending network data */
// CURLE_RECV_ERROR, /* 56 - failure in receiving network data */
// CURLE_OBSOLETE57, /* 57 - NOT IN USE */
// CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */
// CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */
// CURLE_PEER_FAILED_VERIFICATION, /* 60 - peer's certificate or fingerprint
// wasn't verified fine */
// CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */
// CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */
// CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */
// CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */
// CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind
// that failed */
// CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */
// CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not
// accepted and we failed to login */
// CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */
// CURLE_TFTP_PERM, /* 69 - permission problem on server */
// CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */
// CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */
// CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */
// CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */
// CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */
// CURLE_CONV_FAILED, /* 75 - conversion failed */
// CURLE_CONV_REQD, /* 76 - caller must register conversion
// callbacks using curl_easy_setopt options
// CURLOPT_CONV_FROM_NETWORK_FUNCTION,
// CURLOPT_CONV_TO_NETWORK_FUNCTION, and
// CURLOPT_CONV_FROM_UTF8_FUNCTION */
// CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing
// or wrong format */
// CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */
// CURLE_SSH, /* 79 - error from the SSH layer, somewhat
// generic so the error message will be of
// interest when this has happened */
// CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL
// connection */
// CURLE_AGAIN, /* 81 - socket is not ready for send/recv,
// wait till it's ready and try again (Added
// in 7.18.2) */
// CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or
// wrong format (Added in 7.19.0) */
// CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in
// 7.19.0) */
// CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */
// CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */
// CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */
// CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */
// CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */
// CURLE_NO_CONNECTION_AVAILABLE, /* 89 - No connection available, the
// session will be queued */
// CURLE_SSL_PINNEDPUBKEYNOTMATCH, /* 90 - specified pinned public key did not
// match */
// CURLE_SSL_INVALIDCERTSTATUS, /* 91 - invalid certificate status */
// CURLE_HTTP2_STREAM, /* 92 - stream error in HTTP/2 framing layer
// */
// CURLE_RECURSIVE_API_CALL, /* 93 - an api function was called from
// inside a callback */
// CURLE_AUTH_ERROR, /* 94 - an authentication function returned an
// error */
// CURLE_HTTP3, /* 95 - An HTTP/3 layer problem */
// CURL_LAST /* never use! */
// } CURLcode;
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief ()
*
* @return char** NULL字符串表示结尾alloc生成kdk_printer_freeall回收NULL
*/
extern char** kdk_printer_get_list();
/**
* @brief (idle状态)
*
* @return char** NULL字符串表示结尾alloc生成kdk_printer_freeall回收NULL
*/
extern char** kdk_printer_get_available_list();
/**
* @brief ,
*
* @param printername kdk_printer_get_list返回的值
* @param number_up cups属性2 4
* @param media cups属性A4
* @param number_up_layout cups属性lrtb
* @param sides cups属性one-sidedtwo-sided-long-edge(),two-sided-short-edge()
*
* @return
*/
extern void kdk_printer_set_options(int number_up,const char *media,const char *number_up_layout,const char *sides);
/**
* @brief
*
* @param url url
* @param filepath
*
* @return id
*
*/
extern int kdk_printer_print_download_remote_file(const char *url, const char *filepath);
/**
* @brief
*
* @param printername kdk_printer_get_list返回的值
* @param filepath
*
* @return id
*
* @notice pdf之外的格式打印的效果都不够好pdf格式的文件
* stop状态函数返回0
* a.log,
* a.log改名叫a.pdf,a.pdf就变成了格式不对的文件
*
*/
extern int kdk_printer_print_local_file(const char *printername, char *filepath);
/**
* @brief
*
* @param printername kdk_printer_get_list返回的值
*
* @return 0,-1
*
* @notice kdk_printer_print_local_file
*/
extern int kdk_printer_cancel_all_jobs(const char *printername);
/**
* @brief ()
*
* @param printername kdk_printer_get_list返回的值
*
* @return
*/
extern int kdk_printer_get_status(const char *printername);
/**
* @brief ,
*
* @param printername kdk_printer_get_list返回的值
*
* @return
*/
extern int kdk_printer_get_job_status(const char *printername, int jobid);
/**
* @brief url内的文件名
*
* @param url
* @param filename
*
* @return
*/
extern void kdk_printer_get_filename(const char *url, char *filename);
#ifdef __cplusplus
}
#endif
#endif
/**
* @}
*/

View File

@ -0,0 +1,29 @@
#include "../libkyprinter.h"
#include "../libkync.h"
#include <stdio.h>
int main()
{
int index = 0;
//获取全部打印机列表
char **printers = kdk_printer_get_list();
while (printers[index])
{
int status = kdk_printer_get_status(printers[index]);
printf("%zd: %s , %d\n", index + 1, printers[index], status);
index++;
}
kdk_nc_freeall(printers);
//获取可用打印机列表
index = 0;
char **available_printers = kdk_printer_get_list();
while (available_printers[index])
{
int status = kdk_printer_get_status(available_printers[index]);
printf("%zd: %s , %d\n", index + 1, available_printers[index], status);
index++;
}
kdk_nc_freeall(available_printers);
return 0;
}

View File

@ -0,0 +1,51 @@
#include "../libkyprinter.h"
#include "../libkync.h"
#include <stdio.h>
int main()
{
int index = 0;
//获取打印机列表
char **printers = kdk_printer_get_available_list();
while (printers[index])
{
printf("%zd: %s\n", index + 1, printers[index]);
//取消当前打印机所有打印任务
kdk_printer_cancel_all_jobs(printers[index]);
//获取url对应的文件名
char *url = "http://www.cztouch.com/upfiles/soft/testpdf.pdf";
int res = -1;
char *filename = (char *)malloc(sizeof(url)); //申请一个缓冲区,存放接收到的文件内容
memset(filename, 0, sizeof(url));
kdk_printer_get_filename(url, filename); //从完整路径名中解析出文件名称,例如:/home/test/abc.txt,解析完成后为abc.txt
printf("filename = %s\n", filename);
//设置打印参数
kdk_printer_set_options(2, "A4", "lrtb", "two-sided-long-edge");
//下载
res = kdk_printer_print_download_remote_file(url, filename);
printf("[%s] res = %d\n", __FUNCTION__, res);
printf("[%s] filepath = %s\n", __FUNCTION__, filename);
//打印
int job_id = kdk_printer_print_local_file(printers[index], filename);
if (job_id == 0)
{
//打印失败
printf("[%s] create print job fail\n", __FUNCTION__);
}
else
{
//打印成功,等待一会获取任务状态
sleep(10);
int status = kdk_printer_get_job_status(printers[index], job_id);
}
index++;
}
kdk_nc_freeall(printers);
return 0;
}

View File

@ -1,12 +1,13 @@
# include_directories("/usr/include/python3.8")
# add_library(kylocation SHARED libkylocation.c)
# set_target_properties(kylocation PROPERTIES VERSION 2.0.0 SOVERSION 1)
# target_link_libraries(kylocation -lpython3.8)
# add_executable(kylocation-test test/kylocation-test.c)
# target_link_libraries(kylocation-test kylocation)
find_library(GLIBC_LIB glib-2.0)
include_directories("/usr/include/glib-2.0")
add_library(kylocation SHARED libkylocation.c)
set_target_properties(kylocation PROPERTIES VERSION 2.0.0 SOVERSION 1)
target_link_libraries(kylocation -lglib-2.0 -lgio-2.0)
add_executable(kylocation-test test/kylocation-test.c)
target_link_libraries(kylocation-test kylocation)
# install(TARGETS kylocation
# DESTINATION lib/kysdk/kysdk-system)
install(TARGETS kylocation
DESTINATION lib/kysdk/kysdk-system)
# install(FILES libkylocation.h
# DESTINATION include/kysdk/kysdk-system)
install(FILES libkylocation.h
DESTINATION include/kysdk/kysdk-system)

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?> <!-- -*- XML -*- -->
<!DOCTYPE busconfig PUBLIC
"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<!-- Only user root can own the alsa service -->
<policy user="root">
<allow own="com.kysdk.location" />
<allow send_destination="com.kysdk.location" />
<allow receive_sender="com.kysdk.location" />
</policy>
<policy context="default">
<allow send_destination="com.kysdk.location" />
<!-- remove the following line for debug -->
<!--
<allow send_interface="com.jd.ccis"/>
-->
</policy>
</busconfig>

View File

@ -0,0 +1,12 @@
[Unit]
Description=KYLIN DBUS FOR POLICE
[Service]
Type=dbus
Restart=always
RestartSec=0
BusName=com.kysdk.location
ExecStart=/usr/bin/python3 /usr/bin/location.py
[Install]
WantedBy=multi-user.target

View File

@ -1,46 +1,52 @@
#include "Python.h"
#include <gio/gio.h>
#define BUS_NAME "com.kysdk.location"
#define BUS_PATH "/com/kysdk/location"
#define BUS_FACE "com.kysdk.location"
#define METHOD "getAddress"
static GDBusConnection *conn;
static GMainLoop *loop;
static void SearchDeviceCallback(GDBusConnection *connection, GAsyncResult *res, gpointer user_data)
{
GError *error = NULL;
GVariant **ret = (GVariant **)user_data;
*ret = g_dbus_connection_call_finish (connection, res, &error);
g_main_loop_quit(loop);
}
char *kdk_loaction_get()
{
char *location = NULL;
Py_Initialize();
// return pwd->pw_name;
GError *error = NULL;
GVariant *result;
char *user_name;
//相当于在python中的import sys语句。这个函数相当于直接运行python语句
PyRun_SimpleString("import sys");
conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, NULL);
//是将搜索路径设置为当前目录。
PyRun_SimpleString("sys.path.append('/usr/lib/kysdk/kysdk-system')");
// PyRun_SimpleString("from location import getAddress");
// PyRun_SimpleString("print(getAddress())");
PyObject *pModule = NULL;
PyObject *pFunc = NULL;
PyObject *pResult = NULL;
loop = g_main_loop_new(NULL, FALSE);
/* 方法调用 */
g_dbus_connection_call(conn,
BUS_NAME,
BUS_PATH,
BUS_FACE,
METHOD,
NULL,
NULL,
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
(GAsyncReadyCallback)SearchDeviceCallback,
&result);
g_main_loop_run(loop);
if (!result){
g_variant_unref(result);
return "";
}
g_variant_get(result, "(s)", &user_name);
g_variant_unref(result);
return user_name;
pModule = PyImport_ImportModule("location");
if (!pModule)
{
return NULL;
}
pFunc = PyObject_GetAttrString(pModule, "getAddress");
;
if (!pFunc || !PyCallable_Check(pFunc))
{
return NULL;
}
pResult = PyObject_CallObject(pFunc, NULL);
if (!pResult)
{
char tmp[64] = "\0";
FILE *fp = popen("curl cip.cc","r");
fgets(tmp,sizeof(tmp),fp);
if(fgets(tmp,sizeof(tmp),fp))
location = (char *)tmp;
return location;
}
PyArg_Parse(pResult, "s", &location);
Py_DECREF(pFunc);
Py_DECREF(pModule);
Py_Finalize();
return location;
}
}

View File

@ -1,22 +1,48 @@
# -*- coding: UTF-8 -*-
#!/usr/bin/env python3
import re
import json
import requests
# -*- coding: UTF-8 -*-
from base64 import decode
from email.utils import getaddresses
from time import sleep
from traceback import print_tb
from urllib.request import urlopen
import requests
import json
import re
import dbus
import dbus.service
import dbus.mainloop.glib
from gi.repository import GObject as gobject
def getaddr():
text = str(urlopen("http://txt.go.sohu.com/ip/soip").read())
ip = re.findall(r'\d+.\d+.\d+.\d+',text)
return ip[0]
def getAddress():
url = "http://api.map.baidu.com/location/ip"
myParams = {"ak":"4DPAeozisfSCUgSLuC14Ux4iXjeEYNGa","ip":getaddr(),"coor":"bd09ll"}
res = requests.get(url=url,params=myParams)
decoded_u = res.text.encode('utf-8').decode('unicode_escape')
data = json.loads(decoded_u)
if data["status"] == 0 :
return decoded_u
else:
return data["message"]
class AddressBus(dbus.service.Object):
def __init__(self, conn=None, object_path=None):
dbus.service.Object.__init__(self, conn, object_path)
self._last_input = None
def getaddr(self):
text = str(urlopen("http://txt.go.sohu.com/ip/soip").read())
ip = re.findall(r'\d+.\d+.\d+.\d+',text)
return ip[0]
@dbus.service.method('com.kysdk.location', out_signature='s')
def getAddress(self):
url = "http://api.map.baidu.com/location/ip"
myParams = {"ak":"4DPAeozisfSCUgSLuC14Ux4iXjeEYNGa","ip":self.getaddr(),"coor":"bd09ll"}
res = requests.get(url=url,params=myParams)
if res.status_code != 200:
return "Error Code" + res.status_code
decoded_u = res.text.encode('utf-8').decode('unicode_escape')
data = json.loads(decoded_u)
if data["status"] == 0 :
return decoded_u
else:
return data["message"]
if __name__ == '__main__' :
dbus.mainloop.glib.DBusGMainLoop(set_as_default = True)
system_bus = dbus.SystemBus()
name = dbus.service.BusName("com.kysdk.location",system_bus)
object_path = "/com/kysdk/location"
obj = AddressBus(system_bus, object_path)
mainloop = gobject.MainLoop()
mainloop.run()

View File

@ -42,12 +42,12 @@ static void parse_port_state(int *st, int port, FILE *fp)
/* Demangle what the kernel gives us */
sscanf(local_addr, "%08X%08X%08X%08X",
&in6.s6_addr32[0], &in6.s6_addr32[1],
&in6.s6_addr32[2], &in6.s6_addr32[3]);
&in6.s6_addr32[2], &in6.s6_addr32[3]);
inet_ntop(AF_INET6, &in6, addr6, sizeof(addr6));
inet6_aftype.input(1, addr6, &localsas);
sscanf(rem_addr, "%08X%08X%08X%08X",
&in6.s6_addr32[0], &in6.s6_addr32[1],
&in6.s6_addr32[2], &in6.s6_addr32[3]);
&in6.s6_addr32[2], &in6.s6_addr32[3]);
inet_ntop(AF_INET6, &in6, addr6, sizeof(addr6));
inet6_aftype.input(1, addr6, &remsas);
localsas.ss_family = AF_INET6;
@ -79,6 +79,17 @@ int kdk_net_get_port_stat(int port)
return state;
}
int kdk_net_get_multiple_port_stat(int start, int end, int *result)
{
for (int i = start; i <= end; i++)
{
result[i - start] = kdk_net_get_port_stat(i);
if (-1 == result[i - start])
return -1;
}
return 0;
}
prouteMapList kdk_net_get_route()
{
prouteMapList list = NULL, currnode = NULL, prenode = NULL;
@ -124,7 +135,7 @@ prouteMapList kdk_net_get_route()
* : dst为0netmask为0, Gateway不为0
*/
if ((flgs & (RTF_GATEWAY | RTF_UP)) &&
g != 0 && d == 0 && m == 0)
g != 0 && d == 0 && m == 0)
{
currnode = (prouteMapList)calloc(1, sizeof(routeMapList));
if (!currnode)
@ -162,3 +173,103 @@ void kdk_net_free_route(prouteMapList list)
free(tmp);
}
}
pChain kdk_net_get_iptable_rules()
{
pChain result = NULL, tmp = NULL;
char line[512] = "\0";
FILE *fp = popen("iptables -L -n", "r");
if (NULL == fp)
{
pclose(fp);
return NULL;
}
while (fgets(line, 512, fp))
{
if (strstr(line, "Chain"))
{
// 申请Chain内存
if (!result)
{
result = (pChain)calloc(1, sizeof(Chain));
tmp = result;
}
else
{
tmp->next = (pChain)calloc(1, sizeof(Chain));
tmp = tmp->next;
}
if (NULL == tmp)
{
kdk_net_free_chain(result);
result = NULL;
break;
}
int count = sscanf(line, "%*s %s (%[^)]", tmp->total, tmp->policy);
continue;
}
if(!tmp)
continue;
if (strstr(line, "target prot opt source destination"))
continue;
char target[8] = "0", prot[4 + 1] = "0", opt[4 + 1] = "0", source[16] = "0", destination[16] = "0", option[32] = "0";
pChainData tmpData;
int count = sscanf(line, "%s %s %s %s %s %[^\n]", target, prot, opt, source, destination, option);
if (count < 5)
{
continue;
}
// Chain下每条规则申请一个chainData结构体
if (!tmp->data)
{
tmp->data = (pChainData)calloc(1, sizeof(chainData));
tmpData = tmp->data;
}
else
{
tmpData->next = (pChainData)calloc(1, sizeof(chainData));
tmpData = tmpData->next;
}
if (NULL == tmpData)
{
kdk_net_free_chain(result);
result = NULL;
break;
}
if (target)
strcpy(tmpData->target, target);
if (prot)
strcpy(tmpData->prot, prot);
if (opt)
strcpy(tmpData->opt, opt);
if (source)
strcpy(tmpData->source, source);
if (destination)
strcpy(tmpData->destination, destination);
if (option)
strcpy(tmpData->option, option);
}
pclose(fp);
return result;
}
void kdk_net_free_chain(pChain list)
{
pChain tmpChain = NULL;
pChainData tmpData = NULL;
while (list)
{
tmpChain = list;
list = list->next;
while (tmpChain->data)
{
tmpData = tmpChain->data;
tmpChain->data = tmpData->next;
free(tmpData);
}
free(tmpChain);
}
}

View File

@ -13,16 +13,41 @@ extern "C"
struct route *next;
} routeMapList, *prouteMapList;
typedef struct chain_data
{
char target[8];
char prot[4 + 1];
char opt[4 + 1];
char source[16];
char destination[16];
char option[32];
struct chain_data *next;
} chainData, *pChainData;
typedef struct chain
{
char total[16];
char policy[32];
pChainData data;
struct chain *next;
} Chain, *pChain;
/// @brief 获取指定网络端口的状态
/// @param port 端口号
/// @return TCP_ESTABLISHED:0x1 TCP_SYN_SENT:0x2 TCP_SYN_RECV:0x3 TCP_FIN_WAIT1:0x4 TCP_FIN_WAIT2:0x5 \
/// @return TCP_ESTABLISHED:0x1 TCP_SYN_SENT:0x2 TCP_SYN_RECV:0x3 TCP_FIN_WAIT1:0x4 TCP_FIN_WAIT2:0x5 \
TCP_TIME_WAIT:0x6 TCP_CLOSE:0x7 TCP_CLOSE_WAIT:0x8 TCP_LAST_ACL:0x9 TCP_LISTEN:0xa TCP_CLOSING:0xb
extern int kdk_net_get_port_stat(int port);
extern int kdk_net_get_multiple_port_stat(int start, int end, int *result);
extern prouteMapList kdk_net_get_route();
extern void kdk_net_free_route(prouteMapList list);
extern pChain kdk_net_get_iptable_rules();
extern void kdk_net_free_chain(pChain list);
#ifdef __cplusplus
}
#endif

View File

@ -15,4 +15,17 @@ int main(int argc, char *argv[])
printf("please input test port num\n");
else
printf("port:%s's state %d\n", argv[1], kdk_net_get_port_stat(atoi(argv[1])));
pChain chain = kdk_net_get_iptable_rules();
pChain tmpchain = chain;
while(tmpchain)
{
printf("Chain: %s\tpolice: %s\n",tmpchain->total,tmpchain->policy);
pChainData tmpData = tmpchain->data;
if(tmpData)
printf("target: %s\tprot: %s\topt: %s\tsource: %s\tdestination: %s\toption: %s\n",tmpData->target,tmpData->prot,tmpData->opt,
tmpData->source,tmpData->destination,tmpData->option);
printf("\n");
tmpchain = tmpchain->next;
}
}

View File

@ -11,6 +11,92 @@
#include <locale.h>
#include <sys/stat.h>
#define PRG_SOCKET_PFX "socket:["
#define PRG_SOCKET_PFXl (strlen(PRG_SOCKET_PFX))
#define PRG_SOCKET_PFX2 "[0000]:"
#define PRG_SOCKET_PFX2l (strlen(PRG_SOCKET_PFX2))
#define LINE_MAX 4096
#define COLWID 240
#define UPTIME_FILE "/proc/uptime"
#define MEMINFO "/proc/meminfo"
#define MAX_PF_NAME 1024
#define PROC_DIR "/proc"
#define MAX_PROC_NUM 1024
#define PROC_NUM 500
#define BUF_SIZE 1024
static int uptime_fd = -1;
#define LC_NUMERIC __LC_NUMERIC
#define __LC_NUMERIC 1
static char buf[8192];
#define O_RDONLY 00
#define BAD_OPEN_MESSAGE \
"Error: /proc must be mounted\n" \
" To mount /proc at boot you need an /etc/fstab line like:\n" \
" proc /proc proc defaults\n" \
" In the meantime, run \"mount proc /proc -t proc\"\n"
#define FILE_TO_BUF(filename, fd) do{ \
static int local_n; \
if (fd == -1 && (fd = open(filename, O_RDONLY)) == -1) { \
fputs(BAD_OPEN_MESSAGE, stderr); \
fflush(NULL); \
_exit(102); \
} \
lseek(fd, 0L, SEEK_SET); \
if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) { \
perror(filename); \
fflush(NULL); \
_exit(103); \
} \
buf[local_n] = '\0'; \
}while(0)
#define SET_IF_DESIRED(x,y) do{ if(x) *(x) = (y); }while(0)
struct pstat {
long unsigned int utime_ticks;
long unsigned int stime_ticks;
long unsigned int cpu_total_time;
};
/* 进程信息 */
typedef struct process_info
{
long proc_pid; //进程id
char proc_name[128]; //进程名
char proc_command[4096]; //进程启动的命令行,包含启动参数
char proc_uid[128]; //进程所属用户 用户uid
char start_time[128]; //进程启动的时间 (char * ctime(time_t time) 函数返回值Tue Jul 28 08:50:26 2020)
unsigned long utime; //进程cpu使用时间,单位s
double proc_cpu; //进程cpu使用率 %
double proc_mem; //进程mem使用量 %
char proc_state[20]; //进程状态
char proc_time[20]; //进程运行时间
char proc_port[20]; //进程端口号
} process_info;
#define PROCESS_ITEM 14
#define PROC_COMD_NUM 11520
typedef struct {
unsigned long user;
unsigned long nice;
unsigned long system;
unsigned long idle;
}Total_Cpu_Occupy_t;
typedef struct {
unsigned int pid;
unsigned long utime; //user time
unsigned long stime; //kernel time
unsigned long cutime; //all user time
unsigned long cstime; //all dead time
}Proc_Cpu_Occupy_t;
static unsigned long lookup_num(char* buffer, const char* key, unsigned long *res)
{
if (strstartswith(buffer, key) == 0)

View File

@ -20,92 +20,6 @@
extern "C" {
#endif
#define PRG_SOCKET_PFX "socket:["
#define PRG_SOCKET_PFXl (strlen(PRG_SOCKET_PFX))
#define PRG_SOCKET_PFX2 "[0000]:"
#define PRG_SOCKET_PFX2l (strlen(PRG_SOCKET_PFX2))
#define LINE_MAX 4096
#define COLWID 240
#define UPTIME_FILE "/proc/uptime"
#define MEMINFO "/proc/meminfo"
#define MAX_PF_NAME 1024
#define PROC_DIR "/proc"
#define MAX_PROC_NUM 1024
#define PROC_NUM 500
#define BUF_SIZE 1024
static int uptime_fd = -1;
#define LC_NUMERIC __LC_NUMERIC
#define __LC_NUMERIC 1
static char buf[8192];
#define O_RDONLY 00
#define BAD_OPEN_MESSAGE \
"Error: /proc must be mounted\n" \
" To mount /proc at boot you need an /etc/fstab line like:\n" \
" proc /proc proc defaults\n" \
" In the meantime, run \"mount proc /proc -t proc\"\n"
#define FILE_TO_BUF(filename, fd) do{ \
static int local_n; \
if (fd == -1 && (fd = open(filename, O_RDONLY)) == -1) { \
fputs(BAD_OPEN_MESSAGE, stderr); \
fflush(NULL); \
_exit(102); \
} \
lseek(fd, 0L, SEEK_SET); \
if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) { \
perror(filename); \
fflush(NULL); \
_exit(103); \
} \
buf[local_n] = '\0'; \
}while(0)
#define SET_IF_DESIRED(x,y) do{ if(x) *(x) = (y); }while(0)
struct pstat {
long unsigned int utime_ticks;
long unsigned int stime_ticks;
long unsigned int cpu_total_time;
};
/* 进程信息 */
typedef struct process_info
{
long proc_pid; //进程id
char proc_name[128]; //进程名
char proc_command[4096]; //进程启动的命令行,包含启动参数
char proc_uid[128]; //进程所属用户 用户uid
char start_time[128]; //进程启动的时间 (char * ctime(time_t time) 函数返回值Tue Jul 28 08:50:26 2020)
unsigned long utime; //进程cpu使用时间,单位s
double proc_cpu; //进程cpu使用率 %
double proc_mem; //进程mem使用量 %
char proc_state[20]; //进程状态
char proc_time[20]; //进程运行时间
char proc_port[20]; //进程端口号
} process_info;
#define PROCESS_ITEM 14
#define PROC_COMD_NUM 11520
typedef struct {
unsigned long user;
unsigned long nice;
unsigned long system;
unsigned long idle;
}Total_Cpu_Occupy_t;
typedef struct {
unsigned int pid;
unsigned long utime; //user time
unsigned long stime; //kernel time
unsigned long cutime; //all user time
unsigned long cstime; //all dead time
}Proc_Cpu_Occupy_t;
/**
* @brief CPU使用率
*

View File

@ -12,7 +12,6 @@ using namespace KDK_SYSTEM;
RealTimeInfo::RealTimeInfo()
{
}
float RealTimeInfo::kdk_real_get_io_speed()
@ -20,65 +19,81 @@ float RealTimeInfo::kdk_real_get_io_speed()
return 0;
}
float RealTimeInfo::kdk_real_get_net_speed()
float RealTimeInfo::kdk_real_get_net_speed(const char *nc)
{
if(!nc)
return -1;
struct if_speed ndev;
int ret = 0;
memset(&ndev,0,sizeof(ndev));
sprintf(ndev.ifs_name,"enp3s0");
memset(&ndev, 0, sizeof(ndev));
sprintf(ndev.ifs_name, "%s", nc);
ndev.ifs_us = 100000;
ret = get_if_speed(&ndev);
if(ret < 0)
if (ret < 0)
return -1;
return ndev.ifs_ospeed * 1.0/(ndev.ifs_us/1000 * 0.001) / 1024.0f;
return ndev.ifs_ospeed * 1.0 / (ndev.ifs_us / 1000 * 0.001) / 1024.0f;
}
float RealTimeInfo::kdk_real_get_cpu_temperature()
{
char tmp[32] = "\0";
char path[64] = "\0";
for(int i = 1; i; i++)
for (int i = 1; i; i++)
{
memset(path,0,64);
snprintf(path,64,"/sys/class/hwmon/hwmon%d",i);
memset(path, 0, 64);
snprintf(path, 64, "/sys/class/hwmon/hwmon%d", i);
if (0 != access(path, F_OK))
{
snprintf(path,64,"/sys/class/hwmon/hwmon1/temp1_input");
snprintf(path, 64, "/sys/class/hwmon/hwmon1/temp1_input");
break;
}
snprintf(path,64,"/sys/class/hwmon/hwmon%d/name",i);
snprintf(path, 64, "/sys/class/hwmon/hwmon%d/name", i);
if (0 != access(path, F_OK))
continue;
else
snprintf(path,64,"/sys/class/hwmon/hwmon%d/temp1_input",i);
snprintf(path, 64, "/sys/class/hwmon/hwmon%d/temp1_input", i);
}
FILE *fp = fopen(path,"r");
if(fp)
FILE *fp = fopen(path, "r");
if (fp)
{
fgets(tmp,sizeof(tmp),fp);
fgets(tmp, sizeof(tmp), fp);
fclose(fp);
return atof(tmp) / 1000;
float temp = atof(tmp);
return temp < 100 ? temp : temp / 1000;
}
return -1;
}
float RealTimeInfo::kdk_real_get_disk_temperature(const char *name)
{
if (!name)
return -1.0f;
nvmeTemp = "";
sataTemp = "";
if(0 == main_worker(name))
if (0 == main_worker(name))
{
printf("Temp %s\n",nvmeTemp.empty() ? sataTemp.c_str() : nvmeTemp.c_str());
// printf("Temp %s\n",nvmeTemp.empty() ? sataTemp.c_str() : nvmeTemp.c_str());
return atof(nvmeTemp.empty() ? sataTemp.c_str() : nvmeTemp.c_str());
}
return -1;
}
int RealTimeInfo::kdk_real_get_disk_rate(const char *name)
{
if (!name)
return -1;
if (0 == main_worker(name))
{
return rate;
}
return -1;
}
int RealTimeInfo::get_if_dbytes(struct if_info *ndev)
{
if(!ndev)
if (!ndev)
return -1;
struct ifaddrs *ifa_list = NULL;
@ -132,7 +147,7 @@ end:
}
int RealTimeInfo::get_if_speed(struct if_speed *ndev)
{
if(!ndev)
if (!ndev)
return -1;
struct if_info *p1 = NULL, *p2 = NULL;

View File

@ -34,9 +34,10 @@ public:
RealTimeInfo();
public:
float kdk_real_get_io_speed();
float kdk_real_get_net_speed();
float kdk_real_get_net_speed(const char *nc);
float kdk_real_get_cpu_temperature();
float kdk_real_get_disk_temperature(const char *name);
int kdk_real_get_disk_rate(const char *name);
private:
int get_if_dbytes(struct KDK_SYSTEM::if_info *ndev);
int get_if_speed(struct KDK_SYSTEM::if_speed *ndev);

View File

@ -741,11 +741,11 @@ static void print_sata_version_and_speed(unsigned short word222,
const char *verstr = get_sata_version(word222);
const char *maxstr = get_sata_speed(maxspeed);
const char *curstr = get_sata_speed(curspeed);
jout("SATA Version is: %s%s%s%s%s%s\n",
(verstr ? verstr : "Unknown"),
(maxstr ? ", " : ""), (maxstr ? maxstr : ""),
(curstr ? " (current: " : ""), (curstr ? curstr : ""),
(curstr ? ")" : ""));
// jout("SATA Version is: %s%s%s%s%s%s\n",
// (verstr ? verstr : "Unknown"),
// (maxstr ? ", " : ""), (maxstr ? maxstr : ""),
// (curstr ? " (current: " : ""), (curstr ? curstr : ""),
// (curstr ? ")" : ""));
if (verstr)
jglb["sata_version"]["string"] = verstr;
jglb["sata_version"]["value"] = word222 & 0x0fff;
@ -762,7 +762,7 @@ static void print_drive_info(const ata_identify_device *drive,
ata_format_id_string(model, drive->model, sizeof(model) - 1);
ata_format_id_string(serial, drive->serial_no, sizeof(serial) - 1);
ata_format_id_string(firmware, drive->fw_rev, sizeof(firmware) - 1);
/*
// Print model family if known
if (dbentry && *dbentry->modelfamily)
{
@ -829,17 +829,20 @@ static void print_drive_info(const ata_identify_device *drive,
}
jglb["logical_block_size"] = sizes.log_sector_size;
jglb["physical_block_size"] = sizes.phy_sector_size;
}
}*/
// Print nominal media rotation rate if reported
if (rpm)
{
if (rpm == 1)
jout("Rotation Rate: Solid State Device\n");
else if (rpm > 1)
jout("Rotation Rate: %d rpm\n", rpm);
// if (rpm == 1)
// jout("Rotation Rate: Solid State Device\n");
if (rpm > 1)
{
rate = rpm;
// jout("Rotation Rate: %d rpm\n", rpm);
}
else
pout("Rotation Rate: Unknown (0x%04x)\n", -rpm);
// pout("Rotation Rate: Unknown (0x%04x)\n", -rpm);
if (rpm > 0)
jglb["rotation_rate"] = (rpm == 1 ? 0 : rpm);
}
@ -850,9 +853,11 @@ static void print_drive_info(const ata_identify_device *drive,
{
const char *form_factor = get_form_factor(word168);
if (form_factor)
jout("Form Factor: %s\n", form_factor);
;
// jout("Form Factor: %s\n", form_factor);
else
jout("Form Factor: Unknown (0x%04x)\n", word168);
;
// jout("Form Factor: Unknown (0x%04x)\n", word168);
jglb["form_factor"]["ata_value"] = word168;
if (form_factor)
jglb["form_factor"]["name"] = form_factor;
@ -863,10 +868,10 @@ static void print_drive_info(const ata_identify_device *drive,
unsigned short word069 = drive->words047_079[69 - 47];
bool trim_det = !!(word069 & 0x4000), trim_zeroed = !!(word069 & 0x0020);
if (trim_sup || rpm == 1) // HDD: if supported (SMR), SSD: always
jout("TRIM Command: %s%s%s\n",
(!trim_sup ? "Unavailable" : "Available"),
(!(trim_sup && trim_det) ? "" : ", deterministic"),
(!(trim_sup && trim_zeroed) ? "" : ", zeroed"));
// jout("TRIM Command: %s%s%s\n",
// (!trim_sup ? "Unavailable" : "Available"),
// (!(trim_sup && trim_det) ? "" : ", deterministic"),
// (!(trim_sup && trim_zeroed) ? "" : ", zeroed"));
jglb["trim"]["supported"] = trim_sup;
if (trim_sup)
{
@ -879,17 +884,17 @@ static void print_drive_info(const ata_identify_device *drive,
unsigned short zoned_caps = word069 & 0x3;
if (zoned_caps)
{
jout("Zoned Device: %s\n",
(zoned_caps == 0x1 ? "Host Aware Zones" : zoned_caps == 0x2 ? "Device managed zones"
: "Unknown (0x3)"));
// jout("Zoned Device: %s\n",
// (zoned_caps == 0x1 ? "Host Aware Zones" : zoned_caps == 0x2 ? "Device managed zones"
// : "Unknown (0x3)"));
if (zoned_caps < 0x3)
jglb["zoned_device"]["capabilities"] = (zoned_caps == 0x1 ? "host_aware" : "device_managed");
}
// See if drive is recognized
jout("Device is: %s%s%s\n",
(dbentry ? "In smartctl database" : "Not in smartctl database"),
(*dbversion ? " " : ""), (*dbversion ? dbversion : ""));
// jout("Device is: %s%s%s\n",
// (dbentry ? "In smartctl database" : "Not in smartctl database"),
// (*dbversion ? " " : ""), (*dbversion ? dbversion : ""));
jglb["in_smartctl_database"] = !!dbentry;
// Print ATA version
@ -919,7 +924,7 @@ static void print_drive_info(const ata_identify_device *drive,
ataver += " (minor revision not indicated)";
}
}
jout("ATA Version is: %s\n", infofound(ataver.c_str()));
// jout("ATA Version is: %s\n", infofound(ataver.c_str()));
if (!ataver.empty())
{
jglb["ata_version"]["string"] = ataver;
@ -935,7 +940,7 @@ static void print_drive_info(const ata_identify_device *drive,
case 0x0: // PATA
{
char buf[32] = "";
pout("Transport Type: Parallel, %s\n", get_pata_version(word222, buf));
// pout("Transport Type: Parallel, %s\n", get_pata_version(word222, buf));
}
break;
case 0x1: // SATA
@ -944,18 +949,19 @@ static void print_drive_info(const ata_identify_device *drive,
drive->words047_079[77 - 47]);
break;
case 0xe: // PCIe (ACS-4)
pout("Transport Type: PCIe (0x%03x)\n", word222 & 0x0fff);
;
// pout("Transport Type: PCIe (0x%03x)\n", word222 & 0x0fff);
break;
default:
pout("Transport Type: Unknown (0x%04x)\n", word222);
// pout("Transport Type: Unknown (0x%04x)\n", word222);
break;
}
jout_startup_datetime("Local Time is: ");
// jout_startup_datetime("Local Time is: ");
// Print warning message, if there is one
if (dbentry && *dbentry->warningmsg)
pout("\n==> WARNING: %s\n\n", dbentry->warningmsg);
;// pout("\n==> WARNING: %s\n\n", dbentry->warningmsg);
}
static const char *OfflineDataCollectionStatus(unsigned char status_byte)
@ -1521,7 +1527,7 @@ static void PrintSmartAttribWithThres(const ata_smart_values *data,
"%*s|______ P prefailure warning\n",
n, "", n, "", n, "", n, "", n, "", n, "");
}
pout("\n");
// pout("\n");
}
if (!jglb.is_enabled())
@ -1868,7 +1874,7 @@ static void PrintLogPages(const char *type, const unsigned char *data,
P(8), P(9), P(10), P(11), P(12), P(13), P(14), P(15));
#undef P
if ((i & 0x1ff) == 0x1f0)
pout("\n");
;// pout("\n");
}
}
@ -2651,7 +2657,7 @@ static int PrintSmartErrorlog(const ata_smart_errorlog *data,
}
print_on();
if (printing_is_switchable)
pout("\n");
// pout("\n");
print_off();
return data->ata_error_count;
}
@ -2867,7 +2873,7 @@ static int PrintSmartExtErrorLog(ata_device *device,
print_on();
if (printing_is_switchable)
pout("\n");
// pout("\n");
print_off();
return log->device_error_count;
}
@ -3945,7 +3951,7 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
// Print most drive identity information if requested
if (options.drive_info)
{
pout("=== START OF INFORMATION SECTION ===\n");
// pout("=== START OF INFORMATION SECTION ===\n");
print_drive_info(&drive, sizes, rpm, dbentry, dbversion.c_str());
}
@ -3957,8 +3963,9 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
// Packet device ?
if (retid > 0)
{
pout("SMART support is: Unavailable - Packet Interface Devices [this device: %s] don't support ATA SMART\n",
packetdevicetype(retid - 1));
;
// pout("SMART support is: Unavailable - Packet Interface Devices [this device: %s] don't support ATA SMART\n",
// packetdevicetype(retid - 1));
}
else
{
@ -3967,10 +3974,10 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
smart_enabled = ataIsSmartEnabled(&drive);
if (smart_supported < 0)
pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show if SMART supported.\n");
;// pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show if SMART supported.\n");
if (smart_supported && smart_enabled < 0)
{
pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.\n");
// pout("SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.\n");
if (need_smart_support)
{
failuretest(MANDATORY_CMD, returnval |= FAILSMART);
@ -3985,13 +3992,13 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
smart_supported = 1;
if (smart_supported < 0)
pout("SMART support is: Unknown - Try option -s with argument 'on' to enable it.");
;// pout("SMART support is: Unknown - Try option -s with argument 'on' to enable it.");
else if (!smart_supported)
jout("SMART support is: Unavailable - device lacks SMART capability.\n");
;// jout("SMART support is: Unavailable - device lacks SMART capability.\n");
else
{
if (options.drive_info)
jout("SMART support is: Available - device has SMART capability.\n");
;// jout("SMART support is: Available - device has SMART capability.\n");
if (smart_enabled >= 0)
{
if (device->ata_identify_is_cached())
@ -4002,8 +4009,8 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
smart_enabled = ataDoesSmartWork(device);
}
if (options.drive_info)
jout("SMART support is: %s\n",
(smart_enabled ? "Enabled" : "Disabled"));
;// jout("SMART support is: %s\n",
// (smart_enabled ? "Enabled" : "Disabled"));
}
}
}
@ -4152,7 +4159,7 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
// Print the (now possibly changed) power mode if available
if (powername)
pout("Power mode %s %s\n", (powerchg ? "was:" : "is: "), powername);
pout("\n");
// pout("\n");
}
// Exit if SMART is not supported but must be available to proceed
@ -4449,11 +4456,11 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
// all this for a newline!
if (options.smart_disable || options.smart_enable || options.smart_auto_save_disable || options.smart_auto_save_enable || options.smart_auto_offl_disable || options.smart_auto_offl_enable || options.set_aam || options.set_apm || options.set_lookahead || options.set_wcache || options.set_security_freeze || options.set_standby || options.sct_wcache_reorder_set || options.set_dsn)
pout("\n");
// pout("\n");
// START OF READ-ONLY OPTIONS APART FROM -V and -i
if (options.smart_check_status || options.smart_general_values || options.smart_vendor_attrib || options.smart_error_log || options.smart_selftest_log || options.smart_selective_selftest_log || options.smart_ext_error_log || options.smart_ext_selftest_log || options.sct_temp_sts || options.sct_temp_hist)
pout("=== START OF READ SMART DATA SECTION ===\n");
;// pout("=== START OF READ SMART DATA SECTION ===\n");
// Check SMART status
if (options.smart_check_status)
@ -4479,7 +4486,7 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
returnval |= FAILAGE;
}
else
pout("\n");
// pout("\n");
break;
case 1:
@ -4563,7 +4570,7 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
returnval |= FAILAGE;
}
else
pout("\n");
;// pout("\n");
}
print_off();
break;
@ -4812,7 +4819,7 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
if (ataPrintSmartSelfTestlog(&smartselftest, !printing_is_switchable, firmwarebugs))
returnval |= FAILLOG;
print_off();
pout("\n");
// pout("\n");
}
}
}
@ -4838,7 +4845,7 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
if (!printing_is_switchable)
ataPrintSelectiveSelfTestLog(&log, &smartval);
print_off();
pout("\n");
// pout("\n");
}
}
@ -4868,14 +4875,14 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
// Read SCT status
if (ataReadSCTStatus(device, &sts))
{
pout("\n");
// pout("\n");
failuretest(OPTIONAL_CMD, returnval |= FAILSMART);
break;
}
if (options.sct_temp_sts)
{
ataPrintSCTStatus(&sts);
pout("\n");
// pout("\n");
}
}
@ -4898,7 +4905,7 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
break;
}
ataPrintSCTTempHist(&tmh);
pout("\n");
// pout("\n");
}
if (options.sct_temp_int)
@ -4971,7 +4978,7 @@ int ataPrintMain(ata_device *device, const ata_print_options &options)
else
ataPrintSCTErrorRecoveryControl(false, read_timer, write_timer, get_power_on);
}
pout("\n");
// pout("\n");
}
}

View File

@ -204,7 +204,7 @@ static void print_drive_info(const nvme_id_ctrl & id_ctrl, const nvme_id_ns & id
// SMART/Health Information is mandatory
jglb["smart_support"] += { {"available", true}, {"enabled", true} };
jout_startup_datetime("Local Time is: ");
// jout_startup_datetime("Local Time is: ");
}
// Format scaled power value.
@ -487,7 +487,7 @@ static void print_error_log(const nvme_error_log_page * error_log,
if (valid_entries == read_entries && read_entries < max_entries)
pout("... (%u entries not read)\n", max_entries - read_entries);
pout("\n");
// pout("\n");
}
int nvmePrintMain(nvme_device * device, const nvme_print_options & options)
@ -512,7 +512,7 @@ int nvmePrintMain(nvme_device * device, const nvme_print_options & options)
// Print Identify Controller/Namespace info
if (options.drive_info || options.drive_capabilities) {
pout("=== START OF INFORMATION SECTION ===\n");
// pout("=== START OF INFORMATION SECTION ===\n");
nvme_id_ns id_ns; memset(&id_ns, 0, sizeof(id_ns));
unsigned nsid = device->get_nsid();
@ -534,10 +534,10 @@ int nvmePrintMain(nvme_device * device, const nvme_print_options & options)
}
if (options.drive_info)
print_drive_info(id_ctrl, id_ns, nsid, show_all);
// print_drive_info(id_ctrl, id_ns, nsid, show_all);
if (options.drive_capabilities)
print_drive_capabilities(id_ctrl, id_ns, nsid, show_all);
pout("\n");
// pout("\n");
}
// if ( options.smart_check_status || options.smart_vendor_attrib
@ -619,7 +619,7 @@ int nvmePrintMain(nvme_device * device, const nvme_print_options & options)
pout("NVMe Log 0x%02x (0x%04x bytes)\n", options.log_page, read_bytes);
dStrHex(log_buf.data(), read_bytes, 0);
pout("\n");
// pout("\n");
}
return retval;

View File

@ -407,7 +407,7 @@ scsiGetSmartData(scsi_device *device, bool attribs)
jglb["scsi_temperature"]["drive_trip"] = triptemp;
}
}
pout("\n");
// pout("\n");
return err;
}
@ -873,7 +873,7 @@ scsiPrintSeagateCacheLPage(scsi_device *device)
num -= pl;
ucp += pl;
}
pout("\n");
// pout("\n");
}
static void
@ -981,7 +981,7 @@ scsiPrintSeagateFactoryLPage(scsi_device *device)
num -= pl;
ucp += pl;
}
pout("\n");
// pout("\n");
}
static void
@ -1125,7 +1125,7 @@ scsiPrintErrorCounterLog(scsi_device *device)
LOG_RESP_LONG_LEN, truncated);
}
}
pout("\n");
// pout("\n");
}
static const char *self_test_code[] = {
@ -2645,7 +2645,7 @@ show_protocol_specific_port_page(unsigned char *resp, int len)
k += param_len;
ucp += param_len;
}
pout("\n");
// pout("\n");
return 1;
}
@ -2815,26 +2815,26 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
scsi_format_id_string(product, &gBuf[16], 16);
scsi_format_id_string(revision, &gBuf[32], 4);
pout("=== START OF INFORMATION SECTION ===\n");
jout("Vendor: %.8s\n", scsi_vendor);
jglb["scsi_vendor"] = scsi_vendor;
jout("Product: %.16s\n", product);
jglb["scsi_product"] = product;
jglb["scsi_model_name"] = strprintf("%s%s%s",
scsi_vendor, (*scsi_vendor && *product ? " " : ""), product);
// pout("=== START OF INFORMATION SECTION ===\n");
// jout("Vendor: %.8s\n", scsi_vendor);
// jglb["scsi_vendor"] = scsi_vendor;
// jout("Product: %.16s\n", product);
// jglb["scsi_product"] = product;
// jglb["scsi_model_name"] = strprintf("%s%s%s",
// scsi_vendor, (*scsi_vendor && *product ? " " : ""), product);
if (gBuf[32] >= ' ')
{
jout("Revision: %.4s\n", revision);
// jglb["firmware_version"] = revision;
jglb["scsi_revision"] = revision;
// jout("Revision: %.4s\n", revision);
// // jglb["firmware_version"] = revision;
// jglb["scsi_revision"] = revision;
}
if ((scsi_version > 0x3) && (scsi_version < 0x8))
{
char sv_arr[8];
snprintf(sv_arr, sizeof(sv_arr), "SPC-%d", scsi_version - 2);
jout("Compliance: %s\n", sv_arr);
jglb["scsi_version"] = sv_arr;
// jout("Compliance: %s\n", sv_arr);
// jglb["scsi_version"] = sv_arr;
}
}
@ -2865,19 +2865,19 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
char cap_str[64], si_str[64];
format_with_thousands_sep(cap_str, sizeof(cap_str), capacity);
format_capacity(si_str, sizeof(si_str), capacity);
jout("User Capacity: %s bytes [%s]\n", cap_str, si_str);
// jout("User Capacity: %s bytes [%s]\n", cap_str, si_str);
if (srr.lb_size)
jglb["user_capacity"]["blocks"].set_unsafe_uint64(capacity /
srr.lb_size);
jglb["user_capacity"]["bytes"].set_unsafe_uint64(capacity);
jout("Logical block size: %u bytes\n", srr.lb_size);
// jout("Logical block size: %u bytes\n", srr.lb_size);
jglb["logical_block_size"] = srr.lb_size;
if (protect || srr.lb_p_pb_exp)
{
if (srr.lb_p_pb_exp > 0)
{
unsigned pb_size = srr.lb_size * (1 << srr.lb_p_pb_exp);
jout("Physical block size: %u bytes\n", pb_size);
// jout("Physical block size: %u bytes\n", pb_size);
jglb["physical_block_size"] = pb_size;
if (srr.l_a_lba > 0) // not common so cut the clutter
pout("Lowest aligned LBA: %u\n", srr.l_a_lba);
@ -2907,14 +2907,14 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
if (p_i_per_lb > 1)
{
jout("%d protection information intervals per "
"logical block\n",
p_i_per_lb);
// jout("%d protection information intervals per "
// "logical block\n",
// p_i_per_lb);
jglb["scsi_protection_intervals_per_lb"] = srr.prot_type;
}
jout("%d bytes of protection information per logical "
"block\n",
pi_sz * p_i_per_lb);
// jout("%d bytes of protection information per logical "
// "block\n",
// pi_sz * p_i_per_lb);
jglb["scsi_protection_interval_bytes_per_lb"] =
pi_sz * p_i_per_lb;
}
@ -2943,32 +2943,34 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
case 0:
if (lbpme <= 0)
{
jout("LU is fully provisioned");
// jout("LU is fully provisioned");
jglb[lb_prov_j]["name"] = "fully provisioned";
if (lbprz)
jout(" [LBPRZ=%d]\n", lbprz);
;
// jout(" [LBPRZ=%d]\n", lbprz);
else
jout("\n");
;
// jout("\n");
}
else
{
jout("LB provisioning type: not reported [LBPME=1, "
"LBPRZ=%d]\n",
lbprz);
// jout("LB provisioning type: not reported [LBPME=1, "
// "LBPRZ=%d]\n",
// lbprz);
jglb[lb_prov_j]["name"] = "not reported";
}
break;
case 1:
jout("LU is resource provisioned, LBPRZ=%d\n", lbprz);
// jout("LU is resource provisioned, LBPRZ=%d\n", lbprz);
jglb[lb_prov_j]["name"] = "resource provisioned";
break;
case 2:
jout("LU is thin provisioned, LBPRZ=%d\n", lbprz);
// jout("LU is thin provisioned, LBPRZ=%d\n", lbprz);
jglb[lb_prov_j]["name"] = "thin provisioned";
break;
default:
jout("LU provisioning type reserved [%d], LBPRZ=%d\n",
prov_type, lbprz);
// jout("LU provisioning type reserved [%d], LBPRZ=%d\n",
// prov_type, lbprz);
jglb[lb_prov_j]["name"] = "reserved";
break;
}
@ -2981,8 +2983,9 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
else if (1 == lbpme)
{
if (scsi_debugmode > 0)
jout("rcap_16 sets LBPME but no LB provisioning VPD page\n");
jout("Logical block provisioning enabled, LBPRZ=%d\n", lbprz);
;
// jout("rcap_16 sets LBPME but no LB provisioning VPD page\n");
// jout("Logical block provisioning enabled, LBPRZ=%d\n", lbprz);
}
int rpm = scsiGetRPM(device, modese_len, &form_factor, &haw_zbc);
@ -2991,11 +2994,14 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
if (0 == rpm)
; // Not reported
else if (1 == rpm)
jout("Rotation Rate: Solid State Device\n");
;
// jout("Rotation Rate: Solid State Device\n");
else if ((rpm <= 0x400) || (0xffff == rpm))
; // Reserved
else
jout("Rotation Rate: %d rpm\n", rpm);
else{
rate = rpm;
// jout("Rotation Rate: %d rpm\n", rpm);
}
jglb["rotation_rate"] = (rpm == 1 ? 0 : rpm);
}
if (form_factor > 0)
@ -3023,7 +3029,7 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
jglb["form_factor"]["scsi_value"] = form_factor;
if (cp)
{
jout("Form Factor: %s inches\n", cp);
// jout("Form Factor: %s inches\n", cp);
jglb["form_factor"]["name"] = strprintf("%s inches", cp);
}
}
@ -3031,14 +3037,14 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
{
have_zbc = true;
q = "Host aware zoned block capable";
jout("%s\n", q);
// jout("%s\n", q);
jglb[std::string("scsi_") + q] = true;
}
else if (haw_zbc == 2)
{
have_zbc = true;
q = "Device managed zoned block capable";
jout("%s\n", q);
// jout("%s\n", q);
jglb[std::string("scsi_") + q] = true;
}
else
@ -3081,7 +3087,7 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
scsi_decode_lu_dev_id(gBuf + 4, len, s, sizeof(s), &transport);
if (strlen(s) > 0)
{
jout("Logical Unit id: %s\n", s);
// jout("Logical Unit id: %s\n", s);
jglb["logical_unit_id"] = s;
}
}
@ -3102,7 +3108,7 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
gBuf[4 + len] = '\0';
scsi_format_id_string(serial, &gBuf[4], len);
jout("Serial number: %s\n", serial);
// jout("Serial number: %s\n", serial);
jglb["serial_number"] = serial;
}
else if (scsi_debugmode > 0)
@ -3121,23 +3127,23 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
jglb["device_type"]["scsi_value"] = peri_dt;
if (peri_dt < (int)(ARRAY_SIZE(peripheral_dt_arr)))
{
jout("Device type: %s\n", peripheral_dt_arr[peri_dt]);
// jout("Device type: %s\n", peripheral_dt_arr[peri_dt]);
jglb["device_type"]["name"] = peripheral_dt_arr[peri_dt];
}
else
jout("Device type: <%d>\n", peri_dt);
// jout("Device type: <%d>\n", peri_dt);
// See if transport protocol is known
if (transport < 0)
transport = scsiFetchTransportProtocol(device, modese_len);
if ((transport >= 0) && (transport <= 0xf))
{
jout("Transport protocol: %s\n", transport_proto_arr[transport]);
// jout("Transport protocol: %s\n", transport_proto_arr[transport]);
jglb["scsi_transport_protocol"]["name"] = transport_proto_arr[transport];
jglb["scsi_transport_protocol"]["value"] = transport;
}
jout_startup_datetime("Local Time is: ");
// jout_startup_datetime("Local Time is: ");
// See if unit accepts SCSI commands from us
if ((err = scsiTestUnitReady(device)))
@ -3185,8 +3191,8 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
if (!is_tape)
{
print_on();
jout("SMART support is: Unavailable - device lacks SMART "
"capability.\n");
// jout("SMART support is: Unavailable - device lacks SMART "
// "capability.\n");
jglb["smart_support"]["available"] = false;
if (scsi_debugmode > 0)
pout(" [%s]\n", scsiErrString(iec_err));
@ -3199,15 +3205,15 @@ scsiGetDriveInfo(scsi_device *device, uint8_t *peripheral_type,
if (!is_tape)
{
ok = scsi_IsExceptionControlEnabled(&iec);
jout("SMART support is: Available - device has SMART capability.\n"
"SMART support is: %s\n",
ok ? "Enabled" : "Disabled");
// jout("SMART support is: Available - device has SMART capability.\n"
// "SMART support is: %s\n",
// ok ? "Enabled" : "Disabled");
jglb["smart_support"]["available"] = true;
jglb["smart_support"]["enabled"] = ok;
}
ok = scsi_IsWarningEnabled(&iec);
jout("Temperature Warning: %s\n",
ok ? "Enabled" : "Disabled or Not Supported");
// jout("Temperature Warning: %s\n",
// ok ? "Enabled" : "Disabled or Not Supported");
jglb["temperature_warning"]["enabled"] = ok;
return 0;
}
@ -3319,7 +3325,7 @@ scsiPrintTemp(scsi_device *device)
jout("Drive Trip Temperature: %d C\n", trip);
jglb["temperature"]["drive_trip"] = trip;
}
pout("\n");
// pout("\n");
}
static void
@ -3675,7 +3681,7 @@ int scsiPrintMain(scsi_device *device, const scsi_print_options &options)
{
if (powername) // Print power condition if requested -n (nocheck)
pout("Power mode %s %s\n", (powerchg ? "was:" : "is: "), powername);
pout("\n");
// pout("\n");
}
// START OF THE ENABLE/DISABLE SECTION OF THE CODE
@ -3757,14 +3763,15 @@ int scsiPrintMain(scsi_device *device, const scsi_print_options &options)
}
if (options.smart_disable || options.smart_enable ||
options.smart_auto_save_disable || options.smart_auto_save_enable)
pout("\n"); // END OF THE ENABLE/DISABLE SECTION OF THE CODE
// pout("\n"); // END OF THE ENABLE/DISABLE SECTION OF THE CODE
// START OF READ-ONLY OPTIONS APART FROM -V and -i
if (options.smart_check_status || options.smart_ss_media_log ||
options.smart_vendor_attrib || options.smart_error_log ||
options.smart_selftest_log || options.smart_background_log ||
options.sasphy)
pout("=== START OF READ SMART DATA SECTION ===\n");
// pout("=== START OF READ SMART DATA SECTION ===\n");
;
if (options.smart_check_status)
{
@ -3827,7 +3834,6 @@ int scsiPrintMain(scsi_device *device, const scsi_print_options &options)
}
if (options.smart_vendor_attrib)
{
printf("smart_vendor_attrib\n");
if (!checkedSupportedLogPages)
{
scsiGetSupportedLogPages(device);

View File

@ -48,6 +48,7 @@ bool printing_is_switchable = false;
bool printing_is_off = false;
std::string nvmeTemp = "";
std::string sataTemp = "";
int rate = 0;
// Control JSON output
json jglb;
@ -498,6 +499,7 @@ int main_worker(const char *name)
bool print_type_only = false;
{
ataopts.smart_vendor_attrib = scsiopts.smart_vendor_attrib = nvmeopts.smart_vendor_attrib = true;
ataopts.drive_info = scsiopts.drive_info = nvmeopts.drive_info = true;
}
// Store formatted current time for jout_startup_datetime()

View File

@ -73,6 +73,7 @@ extern bool printing_is_switchable;
extern bool printing_is_off;
extern std::string nvmeTemp;
extern std::string sataTemp;
extern int rate;
// Printing control functions
inline void print_on()

View File

@ -7,6 +7,7 @@ int main(int argc, char *argv[])
printf("diskTemp : %f\n", info.kdk_real_get_disk_temperature(argv[argc -1]));
printf("cpuTemp: %f\n", info.kdk_real_get_cpu_temperature());
printf("netSpeed : %f\n", info.kdk_real_get_net_speed());
printf("netSpeed : %f\n", info.kdk_real_get_net_speed(argv[argc -2]));
printf("diskRate : %d\n", info.kdk_real_get_disk_rate(argv[argc -1]));
return 0;
}

View File

@ -22,6 +22,8 @@
#define KYLIN_RELEASE_ID "KYLIN_RELEASE_ID"
#define MAX_LINE 1024
#define BUF_SIZE 1024
static char* get_val_from_file(FILE *fp, const char *key)
{

View File

@ -31,8 +31,6 @@ typedef struct {
char *update_version; //补丁版本
} version_t;
#define BUF_SIZE 1024
/**
* @brief
*