repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
kasshisatari/Kanade | file.h | <filename>file.h<gh_stars>1-10
/* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
void
AddFile(
char* path /* file path */
);
void
GetFilePath(
unsigned long fileId,
char* path
);
unsigned long /* records */
GetFileList(
char* keyword, /* search keyword */
unsigned long pageNo, /* page No. */
unsigned char sort, /* sort kind */
unsigned long* fileIdList, /* file id list */
char* filePathList, /* file path list */
unsigned short *offsetList, /* file name offset list */
unsigned char* recordsInPage, /* records in page */
unsigned long* pageNumber
);
long /* file size */
GetFileDetail(
unsigned long fileId, /* file id */
char* path, /* file path */
char* modifyTime /* modify time */
);
void
InitFile(
void
);
void
OpenFile(
void
);
void
CloseFile(
void
);
void
ResetFile(
void
);
void
LockFile(
void
);
void
UnlockFile(
void
);
unsigned long
GetFileCount(
void
);
unsigned long
GetFileRandomId(
void
);
|
kasshisatari/Kanade | vlc.h | <reponame>kasshisatari/Kanade<filename>vlc.h
/* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
long long
VLCGetPosition(
void
);
void
VLCFadeoutVolume(
void
);
void
VLCStopVideo(
void
);
void
VLCPauseVideo(
void
);
void
VLCFFVideo(
void
);
void
VLCRWVideo(
void
);
void
VLCDownVolume(
void
);
void
VLCUpVolume(
void
);
void
VLCChangeAudioTrack(
void
);
void
VLCInitPlayer(
unsigned char audioOutput,
int* vol,
long long* time
);
void
VLCOpenVideo(
char *path,
unsigned char audioTrack
);
unsigned char
VLCIsPlayingVideo(
void
);
|
kasshisatari/Kanade | vlcwrapper.c | <filename>vlcwrapper.c
/* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <vlc/vlc.h>
/* Receive Buffer Max Size */
#define RECV_MAX 16
/* Fadeout Volume Step */
#define FADE_STEP 5
/* Fadeout Count */
#define FADE_COUNT 15
/* Fadeout Wait */
#define FADE_WAIT 200000
/* Reply Normal */
#define REPLY_NORMAL '1'
/* Reply Stop */
#define REPLY_STOP '0'
/* Return OK */
#define RET_OK 0
/* Return STOP */
#define RET_STOP 1
/* Volume Step */
#define VOL_STEP 5
/* Seek Step */
#define SEEK_STEP 5000
typedef unsigned char (*Func)(int);
unsigned char GetPosition(int);
unsigned char FadeoutVolume(int);
unsigned char StopVideo(int);
unsigned char PauseVideo(int);
unsigned char RWVideo(int);
unsigned char FFVideo(int);
unsigned char DownVolume(int);
unsigned char UpVolume(int);
unsigned char ChangeAudioTrack(int);
unsigned char IsPlayingVideo(int);
/* Path */
static char* path = NULL;
/* Audio Track */
static unsigned char audioTrack = 0;
/* Volume */
static int volume = 0;
/* Receive Buffer */
static unsigned char buffer[RECV_MAX] = {0};
/* Request Command Function Table */
static Func funcTable[] = {
GetPosition,
FadeoutVolume,
StopVideo,
PauseVideo,
RWVideo,
FFVideo,
DownVolume,
UpVolume,
ChangeAudioTrack,
IsPlayingVideo
};
/* Instance */
static libvlc_instance_t* instance = NULL;
/* Player */
static libvlc_media_player_t* player = NULL;
/* Media */
static libvlc_media_t* media = NULL;
unsigned char /* Status */
GetPosition(
int fd /* Descripter */
)
{
/* [[[ 1. Get Position ]]] */
long long playTime = libvlc_media_player_get_time(player);
/* [[[ 2. Reply ]]] */
write(fd, &playTime, sizeof(long long));
return RET_OK;
}
unsigned char /* Status */
FadeoutVolume(
int fd /* Descripter */
)
{
/* [[[ 0. Var ]]] */
/* Fade Count */
int count = 0;
/* Current Volume */
int vol = 0;
/* Reply */
char c = REPLY_NORMAL;
/* [[[ 1. Fadeout Volume ]]] */
for (count=0; count<FADE_COUNT; ++count)
{
/* [[ 1.1. Get Volume ]] */
vol = libvlc_audio_get_volume(player);
/* [[ 1.2. Calcurate Volume ]] */
vol -= FADE_STEP;
/* [[ 1.3. Set Volume ]] */
libvlc_audio_set_volume(player, vol);
/* [[ 1.4. Wait ]] */
usleep(FADE_WAIT);
}
/* [[[ 2. Reply ]]] */
write(fd, &c, 1);
return RET_OK;
}
unsigned char /* Status */
StopVideo(
int fd /* Descripter */
)
{
/* [[[ 0. Var ]]] */
/* Reply */
char c = REPLY_STOP;
/* [[[ 1. Stop Video ]]] */
libvlc_media_player_stop(player);
/* [[[ 2. Reply ]]] */
write(fd, &c, 1);
return RET_STOP;
}
unsigned char /* Status */
PauseVideo(
int fd /* Descripter */
)
{
/* [[[ 0. Var ]]] */
/* Reply */
char c = REPLY_NORMAL;
/* [[[ 1. Pause Video ]]] */
libvlc_media_player_pause(player);
/* [[[ 2. Reply ]]] */
write(fd, &c, 1);
return RET_OK;
}
unsigned char /* Status */
RWVideo(
int fd /* Descripter */
)
{
/* [[[ 0. Var ]]] */
/* Reply */
char c = REPLY_NORMAL;
/* [[[ 1. Get Position ]]] */
long long playTime = libvlc_media_player_get_time(player);
/* [[[ 2. Calcurate Position ]]] */
playTime -= SEEK_STEP;
if (playTime < 0)
{
playTime = 0;
}
/* [[[ 3. Seek ]]] */
libvlc_media_player_set_time(player, playTime);
/* [[[ 4. Reply ]]] */
write(fd, &c, 1);
return RET_OK;
}
unsigned char /* Status */
FFVideo(
int fd /* Descripter */
)
{
/* [[[ 0. Var ]]] */
/* Reply */
char c = REPLY_NORMAL;
/* [[[ 1. Get Position ]]] */
long long playTime = libvlc_media_player_get_time(player);
/* [[[ 2. Calcurate Position ]]] */
playTime += SEEK_STEP;
/* [[[ 3. Seek ]]] */
libvlc_media_player_set_time(player, playTime);
/* [[[ 4. Reply ]]] */
write(fd, &c, 1);
return RET_OK;
}
unsigned char /* Status */
DownVolume(
int fd /* Descripter */
)
{
/* [[[ 0. Var ]]] */
/* Reply */
char c = REPLY_NORMAL;
/* [[[ 1. Calcurate Volume ]]] */
volume -= VOL_STEP;
/* [[[ 2. Set Volume ]]] */
libvlc_audio_set_volume(player, volume);
/* [[[ 3. Reply ]]] */
write(fd, &c, 1);
return RET_OK;
}
unsigned char /* Status */
UpVolume(
int fd /* Descripter */
)
{
/* [[[ 0. Var ]]] */
/* Reply */
char c = REPLY_NORMAL;
/* [[[ 1. Calcureate Volume ]]] */
volume += VOL_STEP;
/* [[[ 2. Set Volume ]]] */
libvlc_audio_set_volume(player, volume);
/* [[[ 3. Reply ]]] */
write(fd, &c, 1);
return RET_OK;
}
unsigned char /* Status */
ChangeAudioTrack(
int fd /* Descripter */
)
{
/* [[[ 0. Var ]]] */
/* Reply */
char c = REPLY_NORMAL;
/* Max Audio Track */
int count = 0;
/* Current Audio Track */
int current = 0;
/* [[[ 1. Get Max Audio Track ]]] */
count = libvlc_audio_get_track_count(player);
if (1 != count)
{
/* < Multiple Audio Track > */
/* [[[ 2. Change Audio Track ]]] */
/* [[ 2.1. Get Current Audio Track ]] */
current = libvlc_audio_get_track(player);
/* [[ 2.2. Calcurate Next Audio Track ]] */
current++;
if (current == count)
{
current = 1;
}
/* [[ 2.3. Set Next Audio Track ]] */
libvlc_audio_set_track(player, current);
}
/* [[[ 3. Reply ]]] */
write(fd, &c, 1);
return RET_OK;
}
unsigned char /* Status */
IsPlayingVideo(
int fd /* Descripter */
)
{
/* [[[ 0. Var ]]] */
/* Reply */
char c = REPLY_NORMAL;
/* [[[ 1. Get Player State ]]] */
if (libvlc_Ended == libvlc_media_player_get_state(player))
{
/* < End > */
/* [[[ 2. Reply End ]]] */
c = REPLY_STOP;
write(fd, &c, 1);
return RET_STOP;
}
/* [[[ 3. Reply Play ]]] */
write(fd, &c, 1);
return RET_OK;
}
int /* Listen Socket */
Listen(void)
{
/* [[[ 0. Var ]]] */
/* Socket */
int sock = 0;
/* Address */
struct sockaddr_un sa = {0};
/* Return Sub-Routines */
int res = 0;
/* [[[ 1. Create Socket ]]] */
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (-1 == sock)
{
/* < Failure > */
fprintf(stderr, "create socket error\n");
return -1;
}
/* [[[ 2. Bind Socket ]]] */
/* [[ 2.1. Set Address ]] */
sa.sun_family = AF_UNIX;
strcpy(sa.sun_path, "/tmp/vlcwrapper");
/* [[ 2.2. Remove Old File ]]*/
remove(sa.sun_path);
/* [[ 2.3. Bind Address to Socket ]] */
res = bind(sock, (struct sockaddr*) &sa, sizeof(struct sockaddr_un));
if (0 != res)
{
/* < Failure > */
fprintf(stderr, "bind socket error\n");
close(sock);
return -1;
}
/* [[[ 3. Listen ]]] */
res = listen(sock, 128);
if (0 != res)
{
/* < Failure > */
fprintf(stderr, "listen socket error\n");
close(sock);
return -1;
}
/* < Success > */
return sock;
}
int /* Accepted Descripter */
Accept(
int sock /* Listen Socket */
)
{
/* [[[ 1. Accept Connection ]]] */
return accept(sock, NULL, NULL);
}
void
Close(
int handle /* Descripter or Socket */
)
{
close(handle);
}
int /* Received Size */
Recv(
int fd, /* Descripter */
unsigned char* buffer, /* Buffer */
size_t size /* Buffer Max Size */
)
{
/* [[[ 1. Read From Descripter To Buffer ]]] */
return read(fd, buffer, size-1);
}
unsigned char /* Status */
Parse(
int fd, /* Descripter */
unsigned char cmd /* Request Command */
)
{
/* [[[ 1. Exec Command ]]] */
return funcTable[cmd - 'A'](fd);
}
void
OpenVideo(
void
)
{
/* [[[ 0. Var ]]] */
/* Command Line Option */
unsigned char option[32] = {0};
/* Instance Option */
const char *arg[] = {"--vout", "mmal_vout"};
/* [[[ 1. Init ]]] */
/* [[ 1.1. Instance ]] */
instance = libvlc_new(2, arg);
/* [[ 1.2. Player ]] */
player = libvlc_media_player_new(instance);
/* [[[ 2. Open ]]] */
/* [[ 2.1. Media ]] */
media = libvlc_media_new_path(instance, path);
sprintf(option, "audio-track=%d", audioTrack);
libvlc_media_add_option(media, option);
/* [[ 2.2. Volume ]] */
libvlc_audio_set_volume(player, volume);
/* [[ 2.3. Set Media ]] */
libvlc_media_player_set_media(player, media);
/* [[ 2.4. Release Media ]] */
libvlc_media_release(media);
/* [[ 2.5. Fullscreen ]] */
libvlc_set_fullscreen(player, 1);
/* [[[ 3. Play ]]] */
libvlc_media_player_play(player);
}
int main(int argc, char **argv)
{
/* [[[ 0. Var ]]] */
/* Socket */
int sock = 0;
/* Descripter */
int fd = 0;
/* Receive Size */
int recvSize = 0;
/* Status */
int status = 0;
/* [[[ 1. Command Line Parameter ]]] */
/* Path */
path = argv[1];
/* Audio Track */
audioTrack = atoi(argv[2]);
/* Volume */
volume = atoi(argv[3]);
/* [[[ 2. Listen ]]] */
sock = Listen();
if (-1 == sock)
{
/* < Failure > */
return 1;
}
/* [[[ 3. Accept ]]] */
fd = Accept(sock);
/* [[[ 4. Open Video ]]] */
OpenVideo();
/* [[[ 5. Request Reply Loop ]]] */
for (;;)
{
recvSize = Recv(fd, buffer, RECV_MAX);
if (-1 == recvSize)
{
/* < Error > */
fprintf(stderr, "recv error\n");
goto end;
}
else if (0 == recvSize)
{
continue;
}
for (int count=0; count<recvSize; ++count)
{
status = Parse(fd, buffer[count]);
if (RET_STOP == status)
{
goto end;
}
}
}
end:
Close(fd);
Close(sock);
return 0;
}
|
kasshisatari/Kanade | player.h | /* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
char*
GetSingerComment(
void
);
char*
GetSinger(
void
);
void
SetPlayingPath(
char* path
);
char*
GetPlayingPath(
void
);
int
GetVolume(
void
);
long long
GetPosition(
void
);
void
FadeoutVolume(
void
);
void
StopVideo(
void
);
void
PauseVideo(
void
);
void
FFVideo(
void
);
void
RWVideo(
void
);
void
DownVolume(
void
);
void
UpVolume(
void
);
void
ChangeAudioTrack(
void
);
void
InitPlayer(
unsigned char audioOutput,
long long *time
);
void
LockPlayer(
void
);
void
UnlockPlayer(
void
);
void
OpenVideo(
char *path,
unsigned char audioTrack
);
unsigned char
IsPlayingVideo(
void
);
|
kasshisatari/Kanade | favorite.c | /* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include "sqlite3.h"
#include "define.h"
#include "favorite.h"
#define DBNAME "favorite.db"
#define SQLTABLE "CREATE TABLE [FAVORITE] ([FAVORITEID] INTEGER,[USERID] INTEGER NOT NULL,[PATH] TEXT NOT NULL,UNIQUE([USERID], [PATH]),PRIMARY KEY(FAVORITEID));"
#define SQLINSERT "INSERT INTO FAVORITE VALUES(?, ?, ?);"
#define SQLDELETE "DELETE FROM FAVORITE WHERE FAVORITEID = ?;"
#define SQLDETAIL "SELECT PATH FROM FAVORITE WHERE FAVORITEID = ?;"
#define SQLLIST "SELECT FAVORITEID, PATH FROM FAVORITE WHERE USERID = ? ORDER BY FAVORITEID ASC LIMIT 30 OFFSET ?;"
#define SQLOPEN "SELECT MAX(FAVORITEID) FROM FAVORITE;"
#define SQLCOUNT "SELECT COUNT(FAVORITEID) FROM FAVORITE WHERE USERID = ?;"
static sqlite3 *db = NULL;
static sqlite3_stmt *insertStmt = NULL;
static sqlite3_stmt *deleteStmt = NULL;
static sqlite3_stmt *listStmt = NULL;
static sqlite3_stmt *openStmt = NULL;
static sqlite3_stmt *countStmt = NULL;
static sqlite3_stmt *detailStmt = NULL;
static unsigned long maxFavoriteId = 0;
static
unsigned long
GetPageNum(
unsigned long records
)
{
if (records % PAGERECORDS)
{
return records / PAGERECORDS + 1;
}
else
{
return records / PAGERECORDS;
}
}
unsigned long /* records */
GetFavoriteList(
unsigned long pageNo,
unsigned short userId,
unsigned long* favoriteIdList,
char* pathList,
unsigned char* recordsInPage,
unsigned long* pageNum
)
{
int ret = 0;
unsigned long records = 0;
unsigned long offset = pageNo * PAGERECORDS;
const unsigned char *p = NULL;
sqlite3_bind_int(countStmt, 1, userId);
sqlite3_step(countStmt);
records = sqlite3_column_int(countStmt, 0);
sqlite3_clear_bindings(countStmt);
sqlite3_reset(countStmt);
if (0 == records)
{
return records;
}
sqlite3_bind_int(listStmt, 1, userId);
sqlite3_bind_int(listStmt, 2, offset);
ret = sqlite3_step(listStmt);
*recordsInPage = 0;
while (SQLITE_ROW == ret)
{
favoriteIdList[*recordsInPage] = sqlite3_column_int(listStmt, 0);
p = sqlite3_column_text(listStmt, 1);
strcpy(&(pathList[*recordsInPage * PATH_LENGTH_MAX]), p);
*recordsInPage = *recordsInPage + 1;
ret = sqlite3_step(listStmt);
}
sqlite3_reset(listStmt);
sqlite3_clear_bindings(listStmt);
*pageNum = GetPageNum(records);
return records;
}
void
GetFavoriteDetail(
unsigned long favoriteId,
char* path
)
{
const unsigned char *p = NULL;
int ret = 0;
sqlite3_bind_int(detailStmt, 1, favoriteId);
ret = sqlite3_step(detailStmt);
if (SQLITE_ROW == ret)
{
p = sqlite3_column_text(detailStmt, 0);
strcpy(path, (const char*)p);
}
else
{
sqlite3_reset(detailStmt);
sqlite3_clear_bindings(detailStmt);
*path = 0;
}
sqlite3_reset(detailStmt);
sqlite3_clear_bindings(detailStmt);
}
unsigned long
AddFavorite(
unsigned short userId,
char* path
)
{
int ret = 0;
maxFavoriteId++;
sqlite3_bind_int(insertStmt, 1, maxFavoriteId);
sqlite3_bind_int(insertStmt, 2, userId);
sqlite3_bind_text(insertStmt, 3, path, strlen(path), SQLITE_TRANSIENT);
ret = sqlite3_step(insertStmt);
if (SQLITE_CONSTRAINT == ret)
{
maxFavoriteId--;
sqlite3_reset(insertStmt);
sqlite3_clear_bindings(insertStmt);
return 0;
}
sqlite3_reset(insertStmt);
sqlite3_clear_bindings(insertStmt);
return maxFavoriteId;
}
void
DeleteFavorite(
unsigned long favoriteId
)
{
sqlite3_bind_int(deleteStmt, 1, favoriteId);
sqlite3_step(deleteStmt);
sqlite3_reset(deleteStmt);
sqlite3_clear_bindings(deleteStmt);
}
void
OpenFavorite(
void
)
{
int ret = 0;
FILE *file = fopen(DBNAME, "r");
if (NULL == file)
{
ResetFavorite();
}
else
{
fclose(file);
}
sqlite3_open(DBNAME, &db);
sqlite3_prepare_v2(db, SQLINSERT, -1, &insertStmt, NULL);
sqlite3_prepare_v2(db, SQLDELETE, -1, &deleteStmt, NULL);
sqlite3_prepare_v2(db, SQLLIST, -1, &listStmt, NULL);
sqlite3_prepare_v2(db, SQLOPEN, -1, &openStmt, NULL);
sqlite3_prepare_v2(db, SQLDETAIL, -1, &detailStmt, NULL);
sqlite3_prepare_v2(db, SQLCOUNT, -1, &countStmt, NULL);
ret = sqlite3_step(openStmt);
if (SQLITE_ROW == ret)
{
maxFavoriteId = (unsigned long)sqlite3_column_int(openStmt, 0);
}
else
{
maxFavoriteId = 0;
}
sqlite3_reset(openStmt);
}
void
CloseFavorite(
void
)
{
sqlite3_finalize(insertStmt);
sqlite3_finalize(deleteStmt);
sqlite3_finalize(detailStmt);
sqlite3_finalize(listStmt);
sqlite3_finalize(openStmt);
sqlite3_finalize(countStmt);
sqlite3_close(db);
}
void
LockFavorite(
void
)
{
}
void
UnlockFavorite(
void
)
{
}
void
ResetFavorite(
void
)
{
char *errMsg = NULL;
CloseFavorite();
remove(DBNAME);
sqlite3_open(DBNAME, &db);
if (SQLITE_OK != sqlite3_exec(db, SQLTABLE, NULL, NULL, &errMsg))
{
sqlite3_free(errMsg);
errMsg = NULL;
}
sqlite3_close(db);
}
|
kasshisatari/Kanade | history.c | /* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include "sqlite3.h"
#include "define.h"
#include "history.h"
#include "user.h"
#define DBNAME "history.db"
#define SQLTABLE "CREATE TABLE [HISTORY] ( [HISTORYID] INTEGER NOT NULL UNIQUE, [USERID] INTEGER NOT NULL, [COMMENT] TEXT, [PATH] TEXT NOT NULL, [PLAYTIME] TEXT NOT NULL, PRIMARY KEY(HISTORYID));"
#define SQLINSERT "INSERT INTO HISTORY VALUES(?, ?, ?, ?, ?);"
#define SQLMAXID "SELECT MAX(HISTORYID) FROM HISTORY;"
#define SQLDELETE "DELETE FROM HISTORY WHERE HISTORYID = ?;"
#define SQLUPDATE "UPDATE HISTORY SET COMMENT = ? WHERE HISTORYID = ?;"
#define SQLHAS "SELECT COUNT(HISTORYID) FROM HISTORY WHERE PATH = ?;"
#define SQLCOUNT "SELECT COUNT(HISTORYID) FROM HISTORY;"
#define SQLLIST "SELECT HISTORYID, USERID, COMMENT, PATH, PLAYTIME FROM HISTORY ORDER BY PLAYTIME DESC LIMIT 30 OFFSET ?;"
#define SQLCSV "SELECT HISTORYID, USERID, COMMENT, PATH, PLAYTIME FROM HISTORY ORDER BY PLAYTIME ASC;"
static pthread_mutex_t lock;
static sqlite3 *db = NULL;
static sqlite3_stmt *insertStmt = NULL;
static sqlite3_stmt *maxIdStmt = NULL;
static sqlite3_stmt *deleteStmt = NULL;
static sqlite3_stmt *updateStmt = NULL;
static sqlite3_stmt *countStmt = NULL;
static sqlite3_stmt *hasStmt = NULL;
static sqlite3_stmt *listStmt = NULL;
static sqlite3_stmt *csvStmt = NULL;
static unsigned long maxHistoryId = 0;
static
unsigned long
GetPageNum(
unsigned long records
)
{
if (records % PAGERECORDS)
{
return records / PAGERECORDS + 1;
}
else
{
return records / PAGERECORDS;
}
}
unsigned long /* records */
GetHistoryList(
unsigned long pageNo,
unsigned long* historyIdList,
unsigned short* userIdList,
char* filePathList,
char* commentList,
char* playTimeList,
unsigned char* recordsInPage,
unsigned long* pageNum
)
{
int ret = 0;
unsigned long records = 0;
unsigned long offset = (pageNo - 1) * PAGERECORDS;
const unsigned char *p = NULL;
sqlite3_step(countStmt);
records = sqlite3_column_int(countStmt, 0);
sqlite3_reset(countStmt);
if (0 == records)
{
return records;
}
sqlite3_bind_int(listStmt, 1, offset);
ret = sqlite3_step(listStmt);
*recordsInPage = 0;
while (SQLITE_ROW == ret)
{
historyIdList[*recordsInPage] = sqlite3_column_int(listStmt, 0);
userIdList[*recordsInPage] = sqlite3_column_int(listStmt, 1);
p = sqlite3_column_text(listStmt, 2);
strcpy(&(commentList[*recordsInPage * COMMENT_LENGTH_MAX]), p);
p = sqlite3_column_text(listStmt, 3);
strcpy(&(filePathList[*recordsInPage * PATH_LENGTH_MAX]), p);
p = sqlite3_column_text(listStmt, 4);
strcpy(&(playTimeList[*recordsInPage * PLAYTIME_LENGTH_MAX]), p);
*recordsInPage = *recordsInPage + 1;
ret = sqlite3_step(listStmt);
}
sqlite3_reset(listStmt);
sqlite3_clear_bindings(listStmt);
*pageNum = GetPageNum(records);
return records;
}
unsigned long /* History ID */
AddHistory(
unsigned short userId,
char* path,
char* comment,
char* playTime
)
{
maxHistoryId++;
sqlite3_bind_int(insertStmt, 1, maxHistoryId);
sqlite3_bind_int(insertStmt, 2, userId);
sqlite3_bind_text(insertStmt, 3, comment, strlen(comment), SQLITE_TRANSIENT);
sqlite3_bind_text(insertStmt, 4, path, strlen(path), SQLITE_TRANSIENT);
sqlite3_bind_text(insertStmt, 5, playTime, strlen(playTime), SQLITE_TRANSIENT);
sqlite3_step(insertStmt);
sqlite3_reset(insertStmt);
sqlite3_clear_bindings(insertStmt);
return maxHistoryId;
}
// #define SQLCSV "SELECT HISTORYID, USERID, COMMENT, PATH, PLAYTIME FROM HISTORY ORDER BY PLAYTIME ASC;"
void
ExtractHistory(
unsigned long historyId,
char* fileName
)
{
int ret = 0;
unsigned char extract = 0;
FILE *file = NULL;
unsigned long histId;
unsigned long userId;
char userName[128];
const char *p = NULL;
const char *song = NULL;
const char *path = NULL;
file = fopen(fileName, "w");
fputc(0xEF, file);
fputc(0xBB, file);
fputc(0xBF, file);
fprintf(file,"time,user,comment,file,path\n");
ret = sqlite3_step(csvStmt);
while (SQLITE_ROW == ret)
{
if (0 == extract)
{
histId = sqlite3_column_int(csvStmt, 0);
if (histId == historyId)
{
extract = 1;
}
}
if (1 == extract)
{
// Time
p = sqlite3_column_text(csvStmt, 4);
fprintf(file, "%s,", p);
// User
userId = sqlite3_column_int(csvStmt, 1);
GetUserName(userId, userName);
fprintf(file, "%s,", userName);
// Comment
p = sqlite3_column_text(csvStmt, 2);
fprintf(file, "%s,", p);
// File
p = sqlite3_column_text(csvStmt, 3);
path = p;
while (0 != *p)
{
if ('/' == *p)
{
song = p + 1;
}
p++;
}
fprintf(file, "%s,", song);
// Path
fprintf(file, "%s\n", path);
}
ret = sqlite3_step(csvStmt);
}
sqlite3_reset(csvStmt);
fclose(file);
}
void
InitHistory(
void
)
{
pthread_mutex_init(&lock, 0);
}
void
OpenHistory(
void
)
{
int ret = 0;
FILE *file = fopen(DBNAME, "r");
if (NULL == file)
{
ResetHistory();
}
else
{
fclose(file);
}
sqlite3_open(DBNAME, &db);
sqlite3_prepare_v2(db, SQLINSERT, -1, &insertStmt, NULL);
sqlite3_prepare_v2(db, SQLMAXID, -1, &maxIdStmt, NULL);
sqlite3_prepare_v2(db, SQLDELETE, -1, &deleteStmt, NULL);
sqlite3_prepare_v2(db, SQLUPDATE, -1, &updateStmt, NULL);
sqlite3_prepare_v2(db, SQLCOUNT, -1, &countStmt, NULL);
sqlite3_prepare_v2(db, SQLLIST, -1, &listStmt, NULL);
sqlite3_prepare_v2(db, SQLHAS, -1, &hasStmt, NULL);
sqlite3_prepare_v2(db, SQLCSV, -1, &csvStmt, NULL);
ret = sqlite3_step(maxIdStmt);
if (SQLITE_ROW == ret)
{
maxHistoryId = sqlite3_column_int(maxIdStmt, 0);
}
else
{
maxHistoryId = 0;
}
sqlite3_reset(maxIdStmt);
sqlite3_finalize(maxIdStmt);
}
void
CloseHistory(
void
)
{
sqlite3_finalize(insertStmt);
sqlite3_finalize(deleteStmt);
sqlite3_finalize(updateStmt);
sqlite3_finalize(countStmt);
sqlite3_finalize(listStmt);
sqlite3_finalize(hasStmt);
sqlite3_finalize(csvStmt);
sqlite3_close(db);
}
void
LockHistory(
void
)
{
pthread_mutex_lock(&lock);
}
void
UnlockHistory(
void
)
{
pthread_mutex_unlock(&lock);
}
void
ResetHistory(
void
)
{
char *errMsg = NULL;
CloseHistory();
remove(DBNAME);
sqlite3_open(DBNAME, &db);
if (SQLITE_OK != sqlite3_exec(db, SQLTABLE, NULL, NULL, &errMsg))
{
sqlite3_free(errMsg);
errMsg = NULL;
}
sqlite3_close(db);
}
void
DeleteHistory(
unsigned long historyId
)
{
sqlite3_bind_int(deleteStmt, 1, historyId);
sqlite3_step(deleteStmt);
sqlite3_reset(deleteStmt);
sqlite3_clear_bindings(deleteStmt);
}
void
ModifyHistory(
unsigned long historyId,
char* comment
)
{
sqlite3_bind_text(updateStmt, 1, comment, strlen(comment), SQLITE_TRANSIENT);
sqlite3_bind_int(updateStmt, 2, historyId);
sqlite3_step(updateStmt);
sqlite3_reset(updateStmt);
sqlite3_clear_bindings(updateStmt);
}
unsigned long /* play counts */
HasHistory(
char* path
)
{
unsigned long count = 0;
sqlite3_bind_text(hasStmt, 1, path, strlen(path), SQLITE_TRANSIENT);
sqlite3_step(hasStmt);
count = (unsigned long)sqlite3_column_int64(hasStmt, 0);
sqlite3_reset(hasStmt);
sqlite3_clear_bindings(hasStmt);
return count;
}
|
kasshisatari/Kanade | favorite.h | /* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
unsigned long /* records */
GetFavoriteList(
unsigned long pageNo,
unsigned short userId,
unsigned long* favoriteIdList,
char* pathList,
unsigned char* recordsInPage,
unsigned long* pageNum
);
void
GetFavoriteDetail(
unsigned long favoriteId,
char* path
);
unsigned long
AddFavorite(
unsigned short userId,
char* path
);
void
DeleteFavorite(
unsigned long favoriteId
);
void
OpenFavorite(
void
);
void
CloseFavorite(
void
);
void
LockFavorite(
void
);
void
UnlockFavorite(
void
);
void
ResetFavorite(
void
);
|
kasshisatari/Kanade | book.h | <reponame>kasshisatari/Kanade
/* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
unsigned char /* records */
GetBookList(
unsigned long* bookIdList,
unsigned short* userIdList,
char* filePathList,
char* commentList,
unsigned long* durationList
);
unsigned long /* Book ID */
AddBook(
unsigned short userId,
char* path,
char* comment,
unsigned long duration,
unsigned char audioTrack,
unsigned char visible
);
unsigned long /* Book ID */
InsertBook(
unsigned short userId,
char* path,
char* comment,
unsigned long duration,
unsigned char audioTrack,
unsigned char visible
);
unsigned long /* Book ID */
AddBreak(
void
);
unsigned long /* Book ID */
InsertBreak(
void
);
unsigned long
DeleteBook(
unsigned long bookId
);
unsigned long /* Book ID */
MoveBook(
unsigned long bookId,
unsigned char dir
);
unsigned char /* Exist */
HasBook(
char* path
);
unsigned long /* Book ID */
ModifyBook(
unsigned long bookId,
char* path,
char* comment,
unsigned long duration,
unsigned char audioTrack,
unsigned char visible
);
void
OpenBook(
void
);
void
CloseBook(
void
);
void
ResetBook(
void
);
void
LockBook(
void
);
void
UnlockBook(
void
);
void
GetBookPath(
unsigned long bookId,
char* path
);
unsigned char
GetBookAudio(
unsigned long bookId
);
void
GetLatestBook(
unsigned long *bookId,
unsigned short *userId,
char *file,
char *comment,
unsigned char *visible
);
|
kasshisatari/Kanade | omxplayer.h | /* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
long long
OMXGetPosition(
void
);
void
OMXFadeoutVolume(
void
);
void
OMXStopVideo(
void
);
void
OMXPauseVideo(
void
);
void
OMXRWVideo(
void
);
void
OMXFFVideo(
void
);
void
OMXDownVolume(
void
);
void
OMXUpVolume(
void
);
void
OMXChangeAudioTrack(
void
);
void
OMXInitPlayer(
unsigned char audioOutput,
int* vol,
long long* time
);
void
OMXOpenVideo(
char *path,
unsigned char audioTrack,
unsigned char audioTrackCount
);
unsigned char
OMXIsPlayingVideo(
void
);
|
kasshisatari/Kanade | history.h | /* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
unsigned long /* records */
GetHistoryList(
unsigned long pageNo,
unsigned long* historyIdList,
unsigned short* userIdList,
char* filePathList,
char* commentList,
char* playTimeList,
unsigned char* recordsInPage,
unsigned long* pageNum
);
unsigned long /* History ID */
AddHistory(
unsigned short userId,
char* path,
char* comment,
char* playTime
);
void
ExtractHistory(
unsigned long historyId,
char* fileName
);
void
InitHistory(
void
);
void
OpenHistory(
void
);
void
CloseHistory(
void
);
void
LockHistory(
void
);
void
UnlockHistory(
void
);
void
ResetHistory(
void
);
void
DeleteHistory(
unsigned long historyId
);
void
ModifyHistory(
unsigned long historyId,
char* comment
);
unsigned long /* play counts */
HasHistory(
char* path
);
|
kasshisatari/Kanade | main.c | /* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netdb.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <memory.h>
#include <pthread.h>
#include <netinet/tcp.h>
#include <dirent.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>
#include <ctype.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <linux/input.h>
#include <libavutil/imgutils.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <gtk/gtk.h>
#include "define.h"
#include "user.h"
#include "file.h"
#include "book.h"
#include "history.h"
#include "favorite.h"
#include "player.h"
#define NOT_FOUND_MESSAGE "HTTP/1.1 404 Not Found\r\nContent-Length:0\r\n\r\n"
#define OK_HEADER "HTTP/1.1 200 OK\r\n"
#define PARTIAL_HEADER "HTTP/1.1 206 OK\r\n"
#define CSV_HEADER "Content-Type: application/octet-stream\r\n"
#define HTML_HEADER "Content-Type: text/html; charset=UTF-8\r\n"
#define CSS_HEADER "Content-Type: text/css; charset=UTF-8\r\n"
#define JS_HEADER "Content-Type: text/javascript; charset=UTF-8\r\n"
#define AVI_HEADER "Content-Type: video/avi\r\n"
#define MP4_HEADER "Content-Type: video/mp4\r\n"
#define MKV_HEADER "Content-Type: video/x-matroska\r\n"
#define FLV_HEADER "Content-Type: video/x-flv\r\n"
#define CONTENT_RANGE_HEADER "Content-Range: bytes %d-"
unsigned char playerState = 0;
long long playTime;
unsigned long playDuration;
unsigned char audioOutput = 0;
unsigned char playMode = 0;
GtkWidget *userLabel = NULL;
GtkWidget *songLabel = NULL;
GtkWidget *commentLabel = NULL;
GtkWidget *pauseLabel = NULL;
int sock = 0;
typedef struct tagSockList
{
int sock;
struct tagSockList *next;
}SockList;
SockList *sockList = NULL;
int sockNum = 0;
void
CopyFileName(
unsigned char* dst,
unsigned char* src,
unsigned char* mediaType
)
{
unsigned char *ext = NULL;
unsigned long fileId = 0;
unsigned char *head = dst;
while(' ' != *src)
{
if ('.' == *src)
{
ext = src + 1;
}
*dst = *src;
fileId = fileId * 10 - '0' + *src;
src++;
dst++;
}
if (NULL == ext)
{
LockFile();
GetFilePath(fileId, head);
UnlockFile();
src = head;
while (0 != *src)
{
if ('.' == *src)
{
ext = src + 1;
}
src++;
}
if ('m' == ext[0])
{
if ('p' == ext[1])
{
*mediaType = 4; // MP4
}
else if ('k' == ext[1])
{
*mediaType = 5; // MKV
}
}
else if ('a' == ext[0])
{
*mediaType = 3; // AVI
}
else if ('f' == ext[0])
{
*mediaType = 6; // FLV
}
return;
}
else if ('c' == ext[0] &&
's' == ext[1] &&
's' == ext[2])
{
*mediaType = 1; // CSS
}
else if('j' == ext[0] &&
's' == ext[1])
{
*mediaType = 2; // JS
}
*dst = 0;
}
void
SendText(
int conn,
unsigned char *str,
int size
)
{
int sendSize = -1;
while(-1 == sendSize)
{
sendSize = send(conn, str, size, 0);
if (EPIPE == errno || ECONNRESET == errno)
{
close(conn);
pthread_exit(NULL);
}
else if (2 == errno)
{
}
else if (0 != errno)
{
fprintf(stderr, "SendText send error %d.\n", errno);
fprintf(stderr, "%s\n", str);
}
}
int offset = 0;
while (sendSize != size)
{
size -= sendSize;
offset += sendSize;
sendSize = -1;
while(-1 == sendSize)
{
sendSize = send(conn, &(str[offset]), size, 0);
if (EPIPE == errno || ECONNRESET == errno)
{
close(conn);
pthread_exit(NULL);
}
else if (2 == errno)
{
}
else if (0 != errno)
{
fprintf(stderr, "SendText send error %d.\n", errno);
}
}
}
}
unsigned long
CheckHeader(
unsigned char* in,
ssize_t size
)
{
int status = 0;
unsigned long count = 0;
for(int i=0;i<size;++i)
{
if (0 == status && '\r' == *in)
{
status++;
in++;
count++;
continue;
}
if (1 == status && '\n' == *in)
{
status++;
in++;
count++;
continue;
}
if (2 == status && '\r' == *in)
{
status++;
in++;
count++;
continue;
}
if (3 == status && '\n' == *in)
{
status++;
in++;
count++;
return count;
}
status = 0;
in++;
count++;
}
return 0;
}
unsigned char*
SkipMessage(
unsigned char* in,
ssize_t rest
)
{
int status = 0;
int count = 0;
unsigned long long maxRest = rest;
for(int i=0;i<maxRest;++i)
{
if (0 == status && '\r' == *in)
{
status++;
in++;
count++;
continue;
}
if (1 == status && '\n' == *in)
{
status++;
in++;
count++;
continue;
}
if (2 == status && '\r' == *in)
{
status++;
in++;
count++;
continue;
}
if (3 == status && '\n' == *in)
{
status++;
in++;
count++;
return in;
}
status = 0;
in++;
count++;
}
return in;
}
unsigned char*
ParseHttpRequest(
unsigned char* in,
unsigned char* fileName,
unsigned char* mediaType,
unsigned long long *begin,
unsigned long long *end,
ssize_t rest,
unsigned char *isRange
)
{
char *range= in;
ssize_t rangeRest = rest;
*begin = 0;
*end = 0;
*isRange = 0;
if (0 == rest)
{
return NULL;
}
if (' ' == in[5])
{
strcpy(fileName,"index.html");
*mediaType = 0; // HTML
}
else
{
CopyFileName(fileName, &(in[5]), mediaType);
}
rest = rest - 5;
while (rangeRest > 0)
{
if ('R' != *range)
{
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if ('a' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if ('n' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if ('g' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if ('e' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if (':' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if (' ' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if ('b' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if ('y' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if ('t' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if ('e' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if ('s' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
if ('=' != *range)
{
continue;
}
++range;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
*isRange = 1;
break;
}
// range = strstr(in, "Range: bytes=");
if (1 == *isRange)
{
while ('0' <= *range && *range <= '9')
{
*begin = *begin * 10 + *range - '0';
range++;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
}
if ('\r' == *range)
{
goto end;
}
if ('-' == *range)
{
range++;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
}
else
{
while ('-' != *range && '\r' != *range)
{
range++;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
}
if ('\r' == *range)
{
goto end;
}
if ('-' == *range)
{
range++;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
}
}
while (*range < '0' || '9' < *range)
{
if ('\r' == *range)
{
goto end;
}
range++;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
}
while ('0' <= *range && *range <= '9')
{
*end = *end * 10 + *range - '0';
range++;
rangeRest--;
if (rangeRest <= 0)
{
goto end;
}
}
}
end:
return SkipMessage(&(in[5]), rest);
}
long long
GetContentSize(
unsigned char *in,
ssize_t size
)
{
int status = 0;
unsigned long long contentSize = 0;
if (size > 0 && 'G' == *in)
{
return 0;
}
if (0 == size)
{
return -1;
}
for(;;)
{
if (('C' == *in && 0 == status) ||
('o' == *in && 1 == status) ||
('n' == *in && 2 == status) ||
('t' == *in && 3 == status) ||
('e' == *in && 4 == status) ||
('n' == *in && 5 == status) ||
('t' == *in && 6 == status) ||
('-' == *in && 7 == status) ||
('L' == *in && 8 == status) ||
('e' == *in && 9 == status))
{
status++;
}
else if (10 != status)
{
status = 0;
}
if (10 == status)
{
in += 5;
while(':' != *in)
{
in++;
size--;
}
in++;
size--;
while(*in < '0' || '9' < *in)
{
in++;
size--;
}
while('\r' != *in && 0 < size)
{
contentSize = contentSize * 10 + *in - '0';
in++;
size--;
}
if ('\r' != *in)
{
return -1;
}
break;
}
in++;
size--;
if (0 == size)
{
return -1;
}
}
return contentSize;
}
void
ResponseConnect(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned char header[256];
unsigned char fileBuf[256];
char *result = NULL;
char pass[256];
char payload[256];
char command[256];
char dateStr[32];
char *p = dateStr;
in++;
size--;
if (size > 0)
{
while (size > 0)
{
*p = *in;
++p;
++in;
--size;
}
*p = 0;
sprintf(command,"sudo date --set=\"%s\" > /dev/null", dateStr);
system(command);
}
FILE *file = NULL;
file = fopen("ip.txt", "r");
fgets(fileBuf, 256, file);
fclose(file);
fileBuf[strlen(fileBuf)-1] = 0;
sprintf(payload, "{\"ip\":\"%s\",", fileBuf);
sprintf(&(payload[strlen(payload)]), "\"port\":\"50000\",");
file = fopen("AccessPointSSID.txt", "r");
fgets(fileBuf, 256, file);
fileBuf[strlen(fileBuf)-1] = 0;
fclose(file);
file = fopen("AccessPointPass.txt", "r");
result = fgets(pass, 256, file);
if (NULL == result)
{
*pass = 0;
}
else
{
pass[strlen(pass)-1] = 0;
}
fclose(file);
sprintf(&(payload[strlen(payload)]), "\"ssid\":\"%s\",", fileBuf);
sprintf(&(payload[strlen(payload)]), "\"pass\":\"%s\"}", pass);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header,"Content-Length:%d\r\n",strlen(payload));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, payload, strlen(payload));
}
void
ResponseLogin(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned char userName[USER_LENGTH_MAX];
unsigned char header[128];
unsigned char payload[8];
unsigned char *dst = userName;
unsigned short userId = 0;
size--;
in++;
for(int i=0;i<size;++i)
{
*dst = *in;
dst++;
in++;
}
*dst = 0;
LockUser();
userId = CreateUser(userName);
UnlockUser();
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(payload, "%d", userId);
sprintf(header, "Content-Length:%d\r\n", strlen(payload));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, payload, strlen(payload));
}
void
WalkDir(
char *path,
unsigned short length
)
{
DIR *dir = NULL;
struct dirent *dp = NULL;
unsigned short len = 0;
dir = opendir(path);
if (NULL == dir)
{
return;
}
path[length] = '/';
path[length + 1] = 0;
for(dp = readdir(dir); NULL != dp; dp = readdir(dir))
{
if (4 == dp->d_type)
{
if ((!strcmp("..", dp->d_name) && 2 == strlen(dp->d_name)) ||
(!strcmp(".", dp->d_name) && 1 == strlen(dp->d_name)) ||
(!strcmp("$RECYCLE.BIN", dp->d_name) && 12 == strlen(dp->d_name)))
{
continue;
}
strcpy(&(path[length + 1]), dp->d_name);
WalkDir(path, strlen(path));
}
else if (8 == dp->d_type)
{
len = strlen(dp->d_name);
if ('4' != dp->d_name[len - 1] ||
'p' != dp->d_name[len - 2] ||
'm' != dp->d_name[len - 3] ||
'.' != dp->d_name[len - 4])
{
if ('i' != dp->d_name[len - 1] ||
'v' != dp->d_name[len - 2] ||
'a' != dp->d_name[len - 3])
{
if ('v' != dp->d_name[len - 1] ||
'k' != dp->d_name[len - 2] ||
'm' != dp->d_name[len - 3])
{
continue;
}
}
}
strcpy(&(path[length + 1]), dp->d_name);
LockFile();
AddFile(path);
UnlockFile();
}
}
closedir(dir);
}
void
UpdateSongService(
void
)
{
char dir[PATH_LENGTH_MAX];
strcpy(dir, "/media/pi");
LockFile();
ResetFile();
OpenFile();
UnlockFile();
WalkDir(dir, strlen("/media/pi"));
strcpy(dir, "/home/pi/Desktop");
WalkDir(dir, strlen("/home/pi/Desktop"));
}
void
ResponseUpdateSong(
int conn,
unsigned char *in,
unsigned long long size
)
{
char header[64];
char *sendBuf = "true";
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header,"Content-Length:%d\r\n",strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
UpdateSongService();
}
void
ResponseSearch(
int conn,
unsigned char *in,
unsigned long long size
)
{
char path[PAGERECORDS][PATH_LENGTH_MAX];
unsigned long fileIdList[PAGERECORDS];
unsigned char recordsInPage = 0;
long pageNum = 0;
unsigned long records = 0;
unsigned short offsetList[PAGERECORDS];
unsigned char sort = 0;
unsigned long page = 0;
unsigned char keyword[1024];
unsigned char *dst = keyword;
unsigned char buf[1024 * 16];
unsigned char header[128];
unsigned long playCount = 0;
int index = 0;
in++;
size--;
if ('1' == *in)
{
sort = 1;
}
in++;
size--;
while(',' != *in)
{
page = page * 10 + *in - '0';
in++;
size--;
}
in++;
size--;
for(int i=0; i<size; ++i)
{
*dst = *in;
in++;
dst++;
}
*dst = 0;
LockFile();
records = GetFileList(
keyword,
page,
sort,
fileIdList,
(char*)path,
offsetList,
&recordsInPage,
&pageNum);
UnlockFile();
index = sprintf(buf, "{\"page\":%d,\"record\":%d,\"files\":[",pageNum, records);
int flag = 0;
LockHistory();
for(int i=0;i<recordsInPage;++i)
{
if (0 == flag)
{
flag = 1;
}
else
{
index += sprintf(&(buf[index]),",");
}
index += sprintf(&(buf[index]), "{\"fileId\":%d,", fileIdList[i]);
playCount = HasHistory(path[i]);
if (0 == playCount)
{
index += sprintf(&(buf[index]), "\"played\":false,");
}
else
{
index += sprintf(&(buf[index]), "\"played\":true,");
}
index += sprintf(&(buf[index]), "\"name\":\"%s\"}", &(path[i][offsetList[i]]));
}
UnlockHistory();
index += sprintf(&(buf[index]), "]}\n");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header,"Content-Length:%d\r\n",index);
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, buf, index);
}
void
ResponseFileDetail(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned long fileId = 0;
unsigned char path[PATH_LENGTH_MAX];
FILE *fp = NULL;
AVFormatContext* formatContext = NULL;
AVDictionaryEntry *dicEntry = NULL;
in++;
size--;
unsigned char audioTrackCount = 0;
unsigned char audioTrackName[16][128];
unsigned char modifyTime[32];
unsigned char sendBuf[1024 * 4];
unsigned char header[128];
long fileSize = 0;
unsigned long length = 0;
unsigned long playCount = 0;
strcpy(sendBuf, "");
while(size > 0)
{
fileId = fileId * 10 + *in - '0';
in++;
size--;
}
LockFile();
fileSize = GetFileDetail(fileId, path, modifyTime);
UnlockFile();
if (-1 == fileSize)
{
// < Not Found >
goto error;
}
sprintf(sendBuf, "{\"path\":\"%s\",\"size\":%d,\"date\":\"%s\",",
path, fileSize, modifyTime);
if (0 != avformat_open_input(&formatContext, path, NULL, NULL))
{
// < Can not open >
goto error;
}
if (0 > avformat_find_stream_info(formatContext, NULL))
{
// < Can not read stream >
goto error;
}
LockHistory();
playCount = HasHistory(path);
UnlockHistory();
sprintf(&(sendBuf[strlen(sendBuf)]), "\"count\":%d,", playCount);
for(int i=0; i<(int)formatContext->nb_streams; ++i)
{
if (AVMEDIA_TYPE_VIDEO == formatContext->streams[i]->codecpar->codec_type)
{
// < Video >
sprintf(&(sendBuf[strlen(sendBuf)]), "\"duration\":%d,",
formatContext->duration/1000000);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"videoCodec\":\"%s\",",
avcodec_get_name(formatContext->streams[i]->codecpar->codec_id));
sprintf(&(sendBuf[strlen(sendBuf)]), "\"resolution\":\"%d x %d\",\"audioTrack\":[",
formatContext->streams[i]->codecpar->width,
formatContext->streams[i]->codecpar->height);
}
else if (AVMEDIA_TYPE_AUDIO == formatContext->streams[i]->codecpar->codec_type)
{
// < Audio >
dicEntry = NULL;
do
{
dicEntry = av_dict_get(formatContext->streams[i]->metadata, "", dicEntry, AV_DICT_IGNORE_SUFFIX);
if (NULL == dicEntry)
{
break;
}
if (!strcmp(dicEntry->key, "handler_name"))
{
break;
}
}while(NULL != dicEntry);
if (NULL != dicEntry)
{
strcpy(audioTrackName[audioTrackCount], dicEntry->value);
}
else
{
strcpy(audioTrackName[audioTrackCount], "None");
}
audioTrackCount++;
}
}
avformat_close_input(&formatContext);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"%s\"", audioTrackName[0]);
for(int i=1; i<audioTrackCount; ++i)
{
sprintf(&(sendBuf[strlen(sendBuf)]), ",\"%s\"", audioTrackName[i]);
}
strcpy(&(sendBuf[strlen(sendBuf)]), "]}");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
return;
error:
strcpy(sendBuf, "{\"path\":\"\"}");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
return;
}
void
ResponsePlayList(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned long bookIdList[PAGERECORDS];
unsigned short userIdList[PAGERECORDS];
unsigned char pathList[PAGERECORDS][PATH_LENGTH_MAX];
unsigned char commentList[PAGERECORDS][COMMENT_LENGTH_MAX];
unsigned long durationList[PAGERECORDS];
unsigned long record = 0;
unsigned char sendBuf[1024 * 64] = { 0 };
unsigned char header[32] = { 0 };
unsigned char userName[USER_LENGTH_MAX] = { 0 };
unsigned char flag = 0;
LockBook();
record = GetBookList(bookIdList, userIdList, (char*)pathList, (char*)commentList, durationList);
UnlockBook();
strcpy(sendBuf, "{\"restCurrentTime\":");
LockPlayer();
if (0 == playerState ||
3 == playerState ||
4 == playerState)
{
sprintf(&(sendBuf[strlen(sendBuf)]), "0,");
}
else
{
sprintf(&(sendBuf[strlen(sendBuf)]), "%d,", playDuration - (playTime/1000));
}
UnlockPlayer();
sprintf(&(sendBuf[strlen(sendBuf)]), "\"playList\":[");
LockUser();
for (int i=0; i<record; ++i)
{
if (0 == flag)
{
flag = 1;
}
else
{
sprintf(&(sendBuf[strlen(sendBuf)]), ",");
}
sprintf(&(sendBuf[strlen(sendBuf)]), "{\"bookId\":%d,", bookIdList[i]);
if (0 == userIdList[i])
{
*userName = 0;
}
else
{
GetUserName(userIdList[i], userName);
}
sprintf(&(sendBuf[strlen(sendBuf)]), "\"user\":\"%s\",", userName);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"path\":\"%s\",", pathList[i]);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"comment\":\"%s\",", commentList[i]);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"duration\":%d}", durationList[i]);
}
UnlockUser();
sprintf(&(sendBuf[strlen(sendBuf)]), "]}");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
GuiPlayList(
)
{
unsigned long bookIdList[PAGERECORDS];
unsigned short userIdList[PAGERECORDS];
unsigned char pathList[PAGERECORDS][PATH_LENGTH_MAX];
unsigned char commentList[PAGERECORDS][COMMENT_LENGTH_MAX];
unsigned long durationList[PAGERECORDS];
unsigned long record = 0;
unsigned char sendBuf[1024 * 64] = { 0 };
unsigned char header[32] = { 0 };
unsigned char userName[USER_LENGTH_MAX] = { 0 };
unsigned char userNameListLabel[PAGERECORDS * USER_LENGTH_MAX] = { 0 };
unsigned char pathListLabel[PAGERECORDS * PATH_LENGTH_MAX] = { 0 };
unsigned char commentListLabel[PAGERECORDS * COMMENT_LENGTH_MAX] = { 0 };
unsigned char *songName = NULL;
unsigned char *songCursor = NULL;
unsigned char pauseStr[128] = { 0 };
LockBook();
record = GetBookList(bookIdList, userIdList, (char*)pathList, (char*)commentList, durationList);
UnlockBook();
sprintf(userNameListLabel, "<span bgcolor=\"#6495ED\" size=\"xx-large\">");
sprintf(pathListLabel, "<span bgcolor=\"#FAF0E6\" size=\"xx-large\">");
sprintf(commentListLabel, "<span bgcolor=\"#FFE4E1\" size=\"xx-large\">");
LockUser();
for (int i=0; i<record; ++i)
{
if (0 == userIdList[i])
{
*userName = 0;
}
else
{
GetUserName(userIdList[i], userName);
}
sprintf(&(userNameListLabel[strlen(userNameListLabel)]), "%s\n", userName);
songCursor = pathList[i];
songName = songCursor;
while (0 != *songCursor)
{
if ('/' == *songCursor)
{
songName = songCursor + 1;
}
songCursor++;
}
sprintf(&(pathListLabel[strlen(pathListLabel)]), "%s\n", songName);
sprintf(&(commentListLabel[strlen(commentListLabel)]), "%s\n", commentList[i]);
}
UnlockUser();
sprintf(&(userNameListLabel[strlen(userNameListLabel)]), "</span>");
sprintf(&(pathListLabel[strlen(pathListLabel)]), "</span>");
sprintf(&(commentListLabel[strlen(commentListLabel)]), "</span>");
if ((2 == playerState) || (3 == playerState) || (5 == playerState))
{
sprintf(pauseStr, "<span bgcolor=\"#FFFFFF\" size=\"xx-large\">Pause</span>");
}
else
{
*pauseStr = 0;
}
gtk_label_set_markup(GTK_LABEL(songLabel), pathListLabel);
gtk_label_set_markup(GTK_LABEL(userLabel), userNameListLabel);
gtk_label_set_markup(GTK_LABEL(commentLabel), commentListLabel);
gtk_label_set_markup(GTK_LABEL(pauseLabel), pauseStr);
}
void
ResponseAddBook(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned char sendBuf[32] = { 0 };
unsigned char header[32] = { 0 };
unsigned short userId = 0;
unsigned long fileId = 0;
unsigned char audio = 0;
long pos = 0;
unsigned char pause = 0;
unsigned char secret = 0;
unsigned char comment[COMMENT_LENGTH_MAX] = { 0 };
unsigned long bookId = 0;
unsigned char *p = comment;
unsigned char path[PATH_LENGTH_MAX] = { 0 };
unsigned long duration = 0;
AVFormatContext* formatContext = NULL;
unsigned char posSign = 0;
in++;
size--;
while(',' != *in)
{
userId = userId * 10 + *in - '0';
in++;
size--;
}
in++;
size--;
while(',' != *in)
{
fileId = fileId * 10 + *in - '0';
in++;
size--;
}
in++;
size--;
audio = *in - '0';
in++;
size--;
posSign = *in;
in++;
size--;
while(',' != *in)
{
pos = *in - '0';
in++;
size--;
}
if ('-' == posSign)
{
pos = -1 * pos;
}
in++;
size--;
pause = *in - '0';
in++;
size--;
secret = *in - '0';
in++;
size--;
while(size>0)
{
*p = *in;
in++;
p++;
size--;
}
if (0 != fileId)
{
LockFile();
GetFilePath(fileId, path);
UnlockFile();
if (0 != avformat_open_input(&formatContext, path, NULL, NULL))
{
// < Can not open >
goto error;
}
if (0 > avformat_find_stream_info(formatContext, NULL))
{
// < Can not read stream >
goto error;
}
duration = formatContext->duration/1000000;
avformat_close_input(&formatContext);
}
if (-2 == pos)
{
if (0 != fileId)
{
LockBook();
bookId = AddBook(userId, path, comment, duration, audio, secret);
UnlockBook();
}
if (1 == pause)
{
LockBook();
bookId = AddBreak();
UnlockBook();
}
}
else if (-1 == pos)
{
if (1 == pause)
{
LockBook();
bookId = InsertBreak();
UnlockBook();
}
if (0 != fileId)
{
LockBook();
bookId = InsertBook(userId, path, comment, duration, audio, secret);
UnlockBook();
}
}
sprintf(sendBuf, "%d", bookId);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
return;
error:
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:1\r\n");
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, "0", 1);
return;
}
void
ResponseDeleteBook(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned char header[32];
unsigned char sendBuf[32];
unsigned long bookId = 0;
in++;
size--;
while(size > 0)
{
bookId = bookId * 10 + *in - '0';
in++;
size--;
}
LockBook();
DeleteBook(bookId);
UnlockBook();
sprintf(sendBuf, "%d", bookId);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseMoveBook(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned long bookId = 0;
unsigned char dir = 1;
unsigned char sendBuf[32];
unsigned char header[32];
in++;
size--;
dir ^= *in - '0';
in++;
size--;
while (size > 0)
{
bookId = bookId * 10 + *in - '0';
size--;
in++;
}
LockBook();
MoveBook(bookId, dir);
UnlockBook();
sprintf(sendBuf, "%d", bookId);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseLatestBook(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned long latestBookId = 0;
char latestUser[USER_LENGTH_MAX];
char latestFile[PATH_LENGTH_MAX];
char latestComment[COMMENT_LENGTH_MAX];
unsigned short latestUserId = 0;
unsigned char latestVisible = 0;
unsigned char sendBuf[1024 * 16];
unsigned char header[32];
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
GetLatestBook(
&latestBookId,
&latestUserId,
latestFile,
latestComment,
&latestVisible);
LockUser();
if (0 == GetUserName(latestUserId, latestUser))
{
latestUser[0] = '\0';
}
UnlockUser();
if (0 == latestBookId)
{
sprintf(sendBuf, "{\"bookId\":0}");
}
else
{
sprintf(sendBuf, "{\"bookId\":%d,", latestBookId);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"user\":\"%s\",", latestUser);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"file\":\"%s\",", latestFile);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"comment\":\"%s\",", latestComment);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"userId\":%d,", latestUserId);
if (0 == latestVisible)
{
sprintf(&(sendBuf[strlen(sendBuf)]), "\"visible\":false}");
}
else
{
sprintf(&(sendBuf[strlen(sendBuf)]), "\"visible\":true}");
}
}
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseHistoryList(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned long pageNo = 0;
unsigned char sendBuf[1024 * 64];
unsigned char header[32];
unsigned long historyIdList[PAGERECORDS];
unsigned short userIdList[PAGERECORDS];
char filePathList[PAGERECORDS][PATH_LENGTH_MAX];
char commentList[PAGERECORDS][COMMENT_LENGTH_MAX];
char playTimeList[PAGERECORDS][20];
char userName[USER_LENGTH_MAX];
unsigned long records = 0;
unsigned char recordInPages = 0;
unsigned long pageNum = 0;
unsigned char flag = 0;
in++;
size--;
while (size > 0)
{
pageNo = pageNo * 10 + *in - '0';
size--;
in++;
}
LockHistory();
records = GetHistoryList(pageNo, historyIdList, userIdList, (char*)filePathList, (char*)commentList, (char*)playTimeList, &recordInPages, &pageNum);
UnlockHistory();
sprintf(sendBuf, "{\"page\":%d,", pageNum);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"record\":%d,", records);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"histories\":[");
LockUser();
for (unsigned char index = 0; index < recordInPages; ++ index)
{
GetUserName(userIdList[index], userName);
if (1 == flag)
{
sprintf(&(sendBuf[strlen(sendBuf)]), ",");
}
else
{
flag = 1;
}
sprintf(&(sendBuf[strlen(sendBuf)]), "{\"historyId\":%d,", historyIdList[index]);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"user\":\"%s\",", userName);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"path\":\"%s\",", filePathList[index]);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"comment\":\"%s\",", commentList[index]);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"time\":\"%s\"}", playTimeList[index]);
}
UnlockUser();
sprintf(&(sendBuf[strlen(sendBuf)]), "]}");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseHistoryCSV(
int conn,
unsigned char *in,
unsigned long long size
)
{
char fileName[32];
char header[128];
char fileBuf[1024*1024];
struct stat st;
FILE *file = NULL;
int fileSize = 0;
unsigned long historyId = 0;
in++;
size--;
while (size > 0)
{
historyId = *in - '0' + historyId;
in++;
size--;
}
sprintf(fileName, "%d.csv", conn);
LockUser();
LockHistory();
ExtractHistory(historyId, fileName);
UnlockHistory();
UnlockUser();
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, CSV_HEADER, strlen(CSV_HEADER));
sprintf(header, "Content-Disposition: attachment; filename=history.csv\r\n");
SendText(conn, header, strlen(header));
stat(fileName, &st);
sprintf(header, "Content-Length:%d\r\n", st.st_size);
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
file = fopen(fileName, "rb");
while (fileSize = fread(fileBuf, sizeof(char), sizeof(fileBuf), file))
{
SendText(conn, fileBuf, fileSize);
}
fclose(file);
remove(fileName);
}
void
ResponseDeleteHistory(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned long historyId = 0;
unsigned char header[32];
unsigned char sendBuf[32];
in++;
size--;
while (size > 0)
{
historyId = historyId * 10 + *in - '0';
in++;
size--;
}
LockHistory();
DeleteHistory(historyId);
UnlockHistory();
sprintf(sendBuf, "%d", historyId);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(OK_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseModifyHistory(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned long historyId = 0;
unsigned char comment[COMMENT_LENGTH_MAX];
unsigned char header[32];
unsigned char sendBuf[32];
unsigned char *dst = comment;
in++;
size--;
while (size > 0 && ',' != *in)
{
historyId = historyId * 10 + *in - '0';
in++;
size--;
}
in++;
size--;
while (size > 0)
{
*dst = *in;
dst++;
in++;
size--;
}
*dst = 0;
LockHistory();
ModifyHistory(historyId, comment);
UnlockHistory();
sprintf(sendBuf, "%d", historyId);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(OK_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ShutdownService(
void
)
{
system("sudo shutdown -h now");
}
void
RestartService(
void
)
{
system("sudo shutdown -r now");
}
void
ResponseSystemDown(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned char header[32];
unsigned char sendBuf[32];
unsigned char off = 0;
in++;
size--;
off = *in - '0';
strcpy(sendBuf, "true");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
if (0 == off)
{
ShutdownService();
}
else
{
RestartService();
}
}
void
ResponseResetHistory(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned char header[32];
unsigned char sendBuf[32];
LockHistory();
ResetHistory();
OpenHistory();
UnlockHistory();
strcpy(sendBuf, "true");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseAddFavorite(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned short userId = 0;
unsigned long favoriteId = 0;
unsigned long fileId = 0;
unsigned char filePath[PATH_LENGTH_MAX] = { 0 };
unsigned char header[32];
unsigned char sendBuf[32];
in++;
size--;
while (',' != *in)
{
fileId = fileId * 10 + *in - '0';
in++;
size--;
}
in++;
size--;
while (size > 0)
{
userId = userId * 10 + *in - '0';
size--;
in++;
}
LockFile();
GetFilePath(fileId, filePath);
UnlockFile();
favoriteId = AddFavorite(userId, filePath);
sprintf(sendBuf, "%d", favoriteId);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseSetAudioConfig(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned char header[32];
unsigned char sendBuf[1024];
unsigned char command[256];
char *result = NULL;
FILE *file = NULL;
in++;
size--;
sprintf(command, "sh confAudio.sh %c", *in);
system(command);
sprintf(sendBuf, "true");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseGetAudioConfig(
int conn,
unsigned char *in,
unsigned long long size
)
{
unsigned char header[32];
unsigned char sendBuf[1024];
unsigned char line[256];
unsigned char firstLine = 1;
unsigned char headChar = '-';
char *result = NULL;
FILE *file = NULL;
*line = '0';
in++;
size--;
system("sh getAudio.sh > getAudio.txt");
system("sh listAudio.sh > listAudio.txt");
file = fopen("getAudio.txt", "r");
fgets(line, 256, file);
line[strlen(line) - 1] = 0;
sprintf(sendBuf,"{\"no\":%s,\"list\":[",line);
fclose(file);
file = fopen("listAudio.txt", "r");
fgets(line, 256, file);
while (*line != headChar)
{
if (1 == firstLine)
{
firstLine = 0;
}
else
{
sprintf(&(sendBuf[strlen(sendBuf)]), ",");
}
line[strlen(line) - 1] = 0;
sprintf(&(sendBuf[strlen(sendBuf)]), "{\"no\":%c,", *line);
sprintf(&(sendBuf[strlen(sendBuf)]), "\"name\":\"%s\"}", &(line[1]));
headChar = *line;
fgets(line, 256, file);
}
sprintf(&(sendBuf[strlen(sendBuf)]), "]}");
fclose(file);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void*
StopVideoWithFade(
void* p
)
{
int i = 0;
int volume = 0;
FadeoutVolume();
LockPlayer();
if (4 == playerState)
{
playerState = 0;
}
else if (5 == playerState)
{
playerState = 3;
}
StopVideo();
UnlockPlayer();
}
void
StopVideoService(
void
)
{
pthread_t thread;
LockPlayer();
if (1 == playerState)
{
playerState = 4;
}
else if (2 == playerState)
{
playerState = 5;
}
pthread_create(&thread, NULL, StopVideoWithFade, NULL);
pthread_detach(thread);
UnlockPlayer();
}
void
ResponseStopVideo(
int conn,
unsigned char *in,
unsigned long long size
)
{
char sendBuf[32];
char header[32];
StopVideoService();
strcpy(sendBuf, "true");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
PauseVideoService(
void
)
{
PauseVideo();
LockPlayer();
if (playerState == 1)
{
playerState = 2;
}
else if (playerState == 2)
{
playerState = 1;
}
else if (playerState == 3)
{
playerState = 0;
}
else if (playerState == 0)
{
playerState = 3;
}
UnlockPlayer();
}
void
ResponsePauseVideo(
int conn,
unsigned char *in,
unsigned long long size
)
{
char sendBuf[32];
char header[32];
PauseVideoService();
strcpy(sendBuf, "true");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseSeekVideo(
int conn,
unsigned char *in,
unsigned long long size
)
{
char sendBuf[32];
char header[32];
in++;
size--;
if ('0' == *in)
{
RWVideo();
}
else if ('1' == *in)
{
FFVideo();
}
sprintf(sendBuf, "%lld", playTime / 1000);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseSetVol(
int conn,
unsigned char *in,
unsigned long long size
)
{
char sendBuf[32];
char header[32];
in++;
size--;
if ('0' == *in)
{
DownVolume();
}
else if ('1' == *in)
{
UpVolume();
}
sprintf(sendBuf, "%d", GetVolume());
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseChangeAudio(
int conn,
unsigned char *in,
unsigned long long size
)
{
char sendBuf[32];
char header[32];
ChangeAudioTrack();
strcpy(sendBuf, "true");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponsePlayInfo(
int conn,
unsigned char *in,
unsigned long long size
)
{
char sendBuf[1024];
char header[32];
int count = 0;
int current = 0;
LockPlayer();
if (0 == playerState)
{
sprintf(sendBuf,"{\"state\":0,\"vol\":%d}",GetVolume());
}
else
{
sprintf(sendBuf,"{\"user\":\"%s\",", GetSinger());
sprintf(&(sendBuf[strlen(sendBuf)]),"\"path\":\"%s\",",GetPlayingPath());
sprintf(&(sendBuf[strlen(sendBuf)]),"\"pos\":%d,",playTime / 1000);
sprintf(&(sendBuf[strlen(sendBuf)]),"\"duration\":%d,",playDuration);
sprintf(&(sendBuf[strlen(sendBuf)]),"\"state\":%d,", playerState);
sprintf(&(sendBuf[strlen(sendBuf)]),"\"comment\":\"%s\",", GetSingerComment());
sprintf(&(sendBuf[strlen(sendBuf)]),"\"vol\":%d}",GetVolume());
}
UnlockPlayer();
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseGetAPConfig(
int conn,
unsigned char *in,
unsigned long long size
)
{
char sendBuf[128];
char pass[128];
char header[32];
char *result = NULL;
system("sh AccessPointPass.sh > AccessPointPass.txt");
FILE *file = fopen("AccessPointPass.txt", "r");
result = fgets(pass, 64, file);
fclose(file);
if (NULL == result)
{
sprintf(sendBuf, "{\"enable\":false}");
}
else
{
pass[strlen(pass) - 1] = 0;
sprintf(sendBuf, "{\"enable\":true, \"phrase\":\"%s\"}", pass);
}
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseUpdateAPConfig(
int conn,
unsigned char *in,
unsigned long long size
)
{
char sendBuf[128];
char pass[128];
char *dst = pass;
char command[256];
char header[32];
char *result = NULL;
in++;
size--;
if ('0' == *in)
{
system("sh disableAccessPointPass.sh");
}
else
{
in++;
size--;
while (size > 0)
{
*dst = *in;
in++;
size--;
dst++;
}
*dst = 0;
sprintf(command, "sh enableAccessPointPass.sh %s", pass);
system(command);
}
sprintf(sendBuf, "true");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseGetPlayMode(
int conn,
unsigned char *in,
unsigned long long size
)
{
char sendBuf[128];
char header[32];
in++;
size--;
sprintf(sendBuf, "{\"mode\":%d}", playMode);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ResponseSetPlayMode(
int conn,
unsigned char *in,
unsigned long long size
)
{
char sendBuf[128];
char header[32];
in++;
size--;
if ('0' == *in)
{
playMode = 0;
}
else if ('1' == *in)
{
playMode = 1;
}
sprintf(sendBuf, "true");
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(header, "Content-Length:%d\r\n", strlen(sendBuf));
SendText(conn, header, strlen(header));
SendText(conn, "\r\n", 2);
SendText(conn, sendBuf, strlen(sendBuf));
}
void
ChangeAudioConfig(
void
)
{
unsigned char config = 0;
unsigned char configMax = 0;
unsigned char configTemp = 0;
unsigned char headChar = '-';
unsigned char command[256];
unsigned char line[256];
FILE *file = NULL;
system("sh getAudio.sh > getAudio.txt");
file = fopen("getAudio.txt", "r");
fgets(line, 256, file);
config = *line - '0';
fclose(file);
system("sh listAudio.sh > listAudio.txt");
file = fopen("listAudio.txt", "r");
fgets(line, 256, file);
while (*line != headChar)
{
configTemp = *line - '0';
if (configMax < configTemp)
{
configMax = configTemp;
}
headChar = *line;
fgets(line, 256, file);
}
config++;
if (config > configMax)
{
config = 0;
}
sprintf(command, "sh confAudio.sh %d", config);
system(command);
}
void
RecvHttpRequest(
ssize_t *recvSize,
int conn,
char *buf,
ssize_t *totalSize,
ssize_t *headerSize,
long long *contentSize,
ssize_t *packetSize,
ssize_t *nextSize
)
{
for(;;)
{
*recvSize = recv(
conn,
buf + *totalSize,
1024 - *totalSize,
0
);
if (-1 == *recvSize)
{
fprintf(stderr,"recv err\n");
close(conn);
pthread_exit(NULL);
}
*totalSize += *recvSize;
if (-1 == *recvSize)
{
if (11 == errno) // Try again
{
continue;
}
break;
}
else if (0 == *recvSize)
{
break;
}
*headerSize = CheckHeader(buf, *totalSize);
if (0 == *headerSize)
{
continue;
}
*contentSize = GetContentSize(buf, *totalSize);
if (-1 == *contentSize)
{
continue;
}
*packetSize = *headerSize + *contentSize;
if (*totalSize < *packetSize)
{
continue;
}
*nextSize = *totalSize - *packetSize;
break;
}
}
void
SendHtmlHeaders(
int conn,
off_t fileSize,
unsigned long begin,
unsigned long end,
unsigned char isRange
)
{
char buf[1024];
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
sprintf(buf,"Content-Length:%d\r\n", fileSize);
SendText(conn, buf, strlen(buf));
SendText(conn, "\r\n", 2);
}
void
SendCssHeaders(
int conn,
off_t fileSize,
unsigned long begin,
unsigned long end,
unsigned char isRange
)
{
char buf[1024];
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, CSS_HEADER, strlen(CSS_HEADER));
sprintf(buf,"Content-Length:%d\r\n", fileSize);
SendText(conn, buf, strlen(buf));
SendText(conn, "\r\n", 2);
}
void
SendJsHeaders(
int conn,
off_t fileSize,
unsigned long begin,
unsigned long end,
unsigned char isRange
)
{
char buf[1024];
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, JS_HEADER, strlen(JS_HEADER));
sprintf(buf,"Content-Length:%d\r\n", fileSize);
SendText(conn, buf, strlen(buf));
SendText(conn, "\r\n", 2);
}
unsigned char
GenerateThumbnail(
char *fileName
)
{
unsigned long fileId = 0;
char filePath[PATH_LENGTH_MAX];
char command[PATH_LENGTH_MAX * 2];
struct stat st = {0};
if ('t' != *fileName)
{
return 0;
}
fileName++;
if ('/' != *fileName)
{
return 0;
}
fileName++;
while ('.' != *fileName)
{
fileId = fileId * 10 + *fileName - '0';
fileName++;
}
LockFile();
GetFilePath(fileId, filePath);
UnlockFile();
sprintf(command, "ffmpeg -ss 10 -t 1 -r 1 -i \"%s\" -f image2 -s 120x90 ", filePath);
sprintf(&command[strlen(command)], "t/%d.png 2> /dev/null", fileId);
system(command);
sprintf(command, "t/%d.png", fileId);
if (0 != stat(command, &st))
{
return 0;
}
return 1;
}
void
ProcessHttpGet(
int conn,
unsigned char *buf,
ssize_t packetSize
)
{
unsigned char fileName[PATH_LENGTH_MAX];
unsigned char mediaType = 0;
unsigned char fileBuf[1500];
unsigned long long begin = 0;
unsigned long long end = 0;
unsigned char isRange = 0;
unsigned long long reqSize = 0;
ParseHttpRequest(buf, fileName, &mediaType, &begin, &end, packetSize, &isRange);
struct stat st;
if (0 != stat(fileName, &st))
{
if (0 == GenerateThumbnail(fileName))
{
SendText(conn, NOT_FOUND_MESSAGE, strlen(NOT_FOUND_MESSAGE));
return;
}
else
{
stat(fileName, &st);
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
}
}
if (0 == mediaType)
{
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, HTML_HEADER, strlen(HTML_HEADER));
}
else if (1 == mediaType)
{
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, CSS_HEADER, strlen(CSS_HEADER));
}
else if (2 == mediaType)
{
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, JS_HEADER, strlen(JS_HEADER));
}
else if (3 == mediaType)
{
if (0 == isRange)
{
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, "Accept-Ranges: bytes\r\n", strlen("Accept-Ranges: bytes\r\n"));
}
else
{
SendText(conn, PARTIAL_HEADER, strlen(PARTIAL_HEADER));
SendText(conn, "Accept-Ranges: bytes\r\n", strlen("Accept-Ranges: bytes\r\n"));
}
SendText(conn, AVI_HEADER, strlen(AVI_HEADER));
if (0 == end)
{
end = st.st_size - 1;
}
if (1 == isRange)
{
sprintf(fileBuf, CONTENT_RANGE_HEADER ,begin);
sprintf(&(fileBuf[strlen(fileBuf)]), "%d/", end);
sprintf(&(fileBuf[strlen(fileBuf)]), "%d\r\n", st.st_size);
SendText(conn, fileBuf, strlen(fileBuf));
}
}
else if (4 == mediaType)
{
if (0 == isRange)
{
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, "Accept-Ranges: bytes\r\n", strlen("Accept-Ranges: bytes\r\n"));
}
else
{
SendText(conn, PARTIAL_HEADER, strlen(PARTIAL_HEADER));
SendText(conn, "Accept-Ranges: bytes\r\n", strlen("Accept-Ranges: bytes\r\n"));
}
SendText(conn, MP4_HEADER, strlen(MP4_HEADER));
if (0 == end)
{
end = st.st_size - 1;
}
if (1 == isRange)
{
sprintf(fileBuf, CONTENT_RANGE_HEADER ,begin);
sprintf(&(fileBuf[strlen(fileBuf)]), "%d/", end);
sprintf(&(fileBuf[strlen(fileBuf)]), "%d\r\n", st.st_size);
SendText(conn, fileBuf, strlen(fileBuf));
}
}
else if (5 == mediaType)
{
if (0 == isRange)
{
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, "Accept-Ranges: bytes\r\n", strlen("Accept-Ranges: bytes\r\n"));
}
else
{
SendText(conn, PARTIAL_HEADER, strlen(PARTIAL_HEADER));
SendText(conn, "Accept-Ranges: bytes\r\n", strlen("Accept-Ranges: bytes\r\n"));
}
SendText(conn, MKV_HEADER, strlen(MKV_HEADER));
if (0 == end)
{
end = st.st_size - 1;
}
if (1 == isRange)
{
sprintf(fileBuf, CONTENT_RANGE_HEADER ,begin);
sprintf(&(fileBuf[strlen(fileBuf)]), "%d/", end);
sprintf(&(fileBuf[strlen(fileBuf)]), "%d\r\n", st.st_size);
SendText(conn, fileBuf, strlen(fileBuf));
}
}
else if (6 == mediaType)
{
if (0 == isRange)
{
SendText(conn, OK_HEADER, strlen(OK_HEADER));
SendText(conn, "Accept-Ranges: bytes\r\n", strlen("Accept-Ranges: bytes\r\n"));
}
else
{
SendText(conn, PARTIAL_HEADER, strlen(PARTIAL_HEADER));
SendText(conn, "Accept-Ranges: bytes\r\n", strlen("Accept-Ranges: bytes\r\n"));
}
SendText(conn, FLV_HEADER, strlen(FLV_HEADER));
if (0 == end)
{
end = st.st_size - 1;
}
if (1 == isRange)
{
sprintf(fileBuf, CONTENT_RANGE_HEADER ,begin);
sprintf(&(fileBuf[strlen(fileBuf)]), "%d/", end);
sprintf(&(fileBuf[strlen(fileBuf)]), "%d\r\n", st.st_size);
SendText(conn, fileBuf, strlen(fileBuf));
}
}
FILE* file = fopen(fileName,"rb");
int fileSize = 0;
unsigned long limitSize = 0;
fseek(file, begin, SEEK_SET);
if (0 == end)
{
end = st.st_size;
}
reqSize = end - begin + 1;
if (1 == isRange)
{
sprintf(fileBuf,"Content-Length:%d\r\n", reqSize);
}
else
{
sprintf(fileBuf,"Content-Length:%d\r\n", st.st_size);
}
SendText(conn, fileBuf, strlen(fileBuf));
SendText(conn, "\r\n", 2);
while(fileSize = fread(fileBuf,sizeof(char),sizeof(fileBuf),file))
{
if (reqSize > fileSize)
{
SendText(conn, fileBuf, fileSize);
}
else
{
SendText(conn, fileBuf, reqSize);
break;
}
reqSize -= fileSize;
}
fclose(file);
}
void*
HttpThread(
void *p
)
{
ssize_t recvSize = 0;
ssize_t totalSize = 0;
ssize_t headerSize = 0;
ssize_t nextSize = 0;
ssize_t packetSize = 0;
unsigned char buf[1024];
int conn = (int)p;
int messageType = 0;
unsigned char *srcP = NULL;
unsigned char *dstP = NULL;
long long contentSize = 0;
unsigned char *message = buf;
int flag = 1;
if (-1 == setsockopt(conn, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(flag)))
{
fprintf(stderr, "Nagle Error \n");
close(conn);
pthread_exit(NULL);
}
for(;;)
{
memcpy(buf, buf + packetSize, nextSize);
totalSize = nextSize;
RecvHttpRequest(
&recvSize, conn, buf, &totalSize, &headerSize,
&contentSize, &packetSize, &nextSize);
if (0 == recvSize)
{
close(conn);
pthread_exit(NULL);
}
if ('G' == *buf)
{
ProcessHttpGet(conn, buf, packetSize);
}
else
{
message = SkipMessage(buf, packetSize);
if ('1' == *message)
{
ResponseConnect(conn, message, contentSize);
}
else if ('0' == *message)
{
ResponseLogin(conn, message, contentSize);
}
else if ('A' == *message)
{
ResponseUpdateSong(conn, message, contentSize);
}
else if ('2' == *message)
{
ResponseSearch(conn, message, contentSize);
}
else if('3' == *message)
{
ResponseFileDetail(conn, message, contentSize);
}
else if ('4' == *message)
{
ResponsePlayList(conn, message, contentSize);
}
else if('5' == *message)
{
ResponseAddBook(conn, message, contentSize);
}
else if('7' == *message)
{
ResponseDeleteBook(conn, message, contentSize);
}
else if('8' == *message)
{
ResponseMoveBook(conn, message, contentSize);
}
else if('B' == *message)
{
ResponseLatestBook(conn, message, contentSize);
}
else if('C' == *message)
{
ResponseHistoryList(conn, message, contentSize);
}
else if('D' == *message)
{
ResponseHistoryCSV(conn, message, contentSize);
}
else if('F' == *message)
{
ResponseDeleteHistory(conn, message, contentSize);
}
else if('G' == *message)
{
ResponseModifyHistory(conn, message, contentSize);
}
else if('L' == *message)
{
ResponseSystemDown(conn, message, contentSize);
}
else if('E' == *message)
{
ResponseResetHistory(conn, message, contentSize);
}
else if('J' == *message)
{
ResponseAddFavorite(conn, message, contentSize);
}
else if('N' == *message)
{
ResponseSetAudioConfig(conn, message, contentSize);
}
else if('O' == *message)
{
ResponseGetAudioConfig(conn, message, contentSize);
}
else if('R' == *message)
{
ResponseStopVideo(conn, message, contentSize);
}
else if('S' == *message)
{
ResponsePauseVideo(conn, message, contentSize);
}
else if('V' == *message)
{
ResponseSeekVideo(conn, message, contentSize);
}
else if('T' == *message)
{
ResponseSetVol(conn, message, contentSize);
}
else if('U' == *message)
{
ResponseChangeAudio(conn, message, contentSize);
}
else if('X' == *message)
{
ResponsePlayInfo(conn, message, contentSize);
}
else if('Y' == *message)
{
ResponseGetAPConfig(conn, message, contentSize);
}
else if('Z' == *message)
{
ResponseUpdateAPConfig(conn, message, contentSize);
}
else if('a' == *message)
{
ResponseGetPlayMode(conn, message, contentSize);
}
else if('b' == *message)
{
ResponseSetPlayMode(conn, message, contentSize);
}
else
{
fprintf(stderr, "%s\n%s\n%d\n%c", buf, message, contentSize, *message);
}
}
}
}
void*
KeyPadThread(
void *p
)
{
struct input_event event;
unsigned char flag = 0;
int in = -1;
for(;;)
{
if (-1 == in)
{
in = open("/dev/input/event0", O_RDONLY | O_NONBLOCK);
fcntl(in, F_SETFL, 0);
continue;
}
if (read(in, &event, sizeof(event)) != sizeof(event))
{
close(in);
in = -1;
continue;
}
switch(event.type)
{
case EV_KEY:
if (0 == event.value)
{
/* < Release > */
switch(event.code)
{
case KEY_KPENTER:
flag = 0;
break;
default:
break;
}
}
else if (1 == event.value)
{
/* < Press > */
switch(event.code)
{
case KEY_KP0:
if (1 == flag)
{
StopVideoService();
}
break;
case KEY_KP2:
DownVolume();
break;
case KEY_KP4:
RWVideo();
break;
case KEY_KP5:
PauseVideoService();
break;
case KEY_KP6:
FFVideo();
break;
case KEY_KP8:
UpVolume();
break;
case KEY_KP9:
if (1 == flag)
{
ChangeAudioConfig();
}
break;
case KEY_KPMINUS:
if (1 == flag)
{
RestartService();
}
break;
case KEY_KPPLUS:
if (1 == flag)
{
UpdateSongService();
}
break;
case KEY_KPSLASH:
if (1 == flag)
{
playMode ^= 1;
}
break;
case KEY_KPASTERISK:
if (1 == flag)
{
ShutdownService();
}
break;
case KEY_KPENTER:
flag = 1;
break;
case KEY_KPDOT:
if (1 == flag)
{
ChangeAudioTrack();
}
break;
default:
break;
}
}
else if (2 == event.value)
{
/* < Repeat > */
}
break;
default:
break;
}
}
}
void*
PlayThread(
void *p
)
{
unsigned long bookIdList[PAGERECORDS];
unsigned short userIdList[PAGERECORDS];
char pathList[PAGERECORDS][PATH_LENGTH_MAX];
char path[PATH_LENGTH_MAX];
char commentList[PAGERECORDS][COMMENT_LENGTH_MAX];
unsigned long durationList[PAGERECORDS];
unsigned char record = 0;
unsigned char currentTime[32];
unsigned char audioTrack = 0;
unsigned char option[32];
unsigned long fileCount = 0;
AVFormatContext *formatContext = NULL;
unsigned long fileId = 0;
playerState = 0;
InitPlayer(audioOutput, &playTime);
for(;;)
{
LockBook();
record = GetBookList(bookIdList, userIdList, (char*)pathList, (char*)commentList, durationList);
UnlockBook();
LockPlayer();
if (0 != record && 0 == playerState)
{
if (!strcmp(pathList[0], "Break"))
{
playerState = 3;
LockBook();
DeleteBook(bookIdList[0]);
UnlockBook();
UnlockPlayer();
continue;
}
sleep(3);
LockBook();
GetBookPath(bookIdList[0], path);
audioTrack = GetBookAudio(bookIdList[0]);
UnlockBook();
OpenVideo(path, audioTrack);
SetPlayingPath(pathList[0]);
strcpy(GetSingerComment(), commentList[0]);
playDuration = durationList[0];
LockUser();
GetUserName(userIdList[0], GetSinger());
UnlockUser();
time_t t = time(NULL);
strftime(currentTime, sizeof(currentTime), "%Y/%m/%d %H:%M:%S", localtime(&t));
LockHistory();
AddHistory(userIdList[0], path, commentList[0], currentTime);
UnlockHistory();
LockBook();
DeleteBook(bookIdList[0]);
UnlockBook();
playerState = 1;
}
else if (0 == record && 0 == playerState && 1 == playMode)
{
/* < Shuffle Mode > */
fileCount = GetFileCount();
if (0 != fileCount)
{
fileId = GetFileRandomId();
GetFilePath(fileId, path);
OpenVideo(path, 0);
SetPlayingPath(path);
avformat_open_input(&formatContext, path, NULL, NULL);
avformat_find_stream_info(formatContext, NULL);
for (int i=0; i<(int)formatContext->nb_streams; ++i)
{
if (AVMEDIA_TYPE_VIDEO == formatContext->streams[i]->codecpar->codec_type)
{
playDuration = formatContext->duration/1000000;
break;
}
}
avformat_close_input(&formatContext);
playerState = 1;
}
}
else
{
if (0 == IsPlayingVideo())
{
if ((1 == playerState) || (2 == playerState) || (4 == playerState) || (5 == playerState))
{
playerState = 0;
}
StopVideo();
}
else
{
playTime = GetPosition();
}
}
UnlockPlayer();
usleep(500000);
}
}
gboolean
timer_handler(
void
)
{
GuiPlayList();
return TRUE;
}
void
abrt_handler(
int sig
)
{
if (-1 == shutdown(sock, SHUT_RDWR))
{
fprintf(stderr, "shutdown server socket: %d\n", errno);
}
if (-1 == close(sock))
{
fprintf(stderr, "close server socket: %d\n", errno);
}
for(SockList *p=sockList;NULL != p;p = p->next)
{
if (-1 == shutdown(p->sock, SHUT_RDWR))
{
fprintf(stderr, "shutdown http socket: %d\n", errno);
}
if (-1 == close(p->sock))
{
fprintf(stderr, "close http socket: %d\n", errno);
}
}
exit(0);
}
void
Exit(
void
)
{
abort();
}
void*
GuiThread(
void *p
)
{
GtkWidget *window = NULL;
GtkWidget *vbox = NULL;
GtkWidget *topBox = NULL;
GtkWidget *listTextBox = NULL;
GtkWidget *hTextBox = NULL;
GtkWidget *hImageBox = NULL;
GtkWidget *wifiLabel = NULL;
GtkWidget *urlLabel = NULL;
GtkWidget *wifiImage = NULL;
GtkWidget *urlImage = NULL;
GtkWidget *quitButton = NULL;
GtkWidget *kanadeImage = NULL;
GtkCssProvider *provider = NULL;
GtkStyleContext *context = NULL;
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
quitButton = gtk_button_new_with_label("X");
gtk_container_set_border_width(GTK_CONTAINER(window), 10);
vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
topBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
listTextBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
hTextBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
hImageBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
songLabel = gtk_label_new(NULL);
userLabel = gtk_label_new(NULL);
pauseLabel = gtk_label_new(NULL);
commentLabel = gtk_label_new(NULL);
provider = gtk_css_provider_new();
context = gtk_widget_get_style_context(window);
gtk_style_context_add_provider(context, GTK_STYLE_PROVIDER(provider),
GTK_STYLE_PROVIDER_PRIORITY_USER);
gtk_widget_set_name(window, "window");
gtk_css_provider_load_from_data(provider,
"window {\n"
" background-color: white;\n"
"}\n",
-1, NULL);
g_object_unref(provider);
char fileBuf[256];
char wifiLabelStr[256];
char urlLabelStr[256];
char pass[256];
FILE *file = NULL;
file = fopen("ip.txt", "r");
fgets(fileBuf, 256, file);
fclose(file);
fileBuf[strlen(fileBuf)-1] = 0;
sprintf(urlLabelStr, "<span bgcolor=\"#FFFFFF\" size=\"xx-large\">Second, go to the following URL.\nhttp://%s:50000/</span>", fileBuf);
file = fopen("AccessPointSSID.txt", "r");
fgets(fileBuf, 256, file);
fileBuf[strlen(fileBuf)-1] = 0;
fclose(file);
file = fopen("AccessPointPass.txt", "r");
char *result = fgets(pass, 256, file);
if (NULL == result)
{
*pass = 0;
}
else
{
pass[strlen(pass)-1] = 0;
}
fclose(file);
sprintf(wifiLabelStr, "<span bgcolor=\"#FFFFFF\" size=\"xx-large\">First, connect the following Wi-Fi.\nSSID:%s\n", fileBuf);
sprintf(&wifiLabelStr[strlen(wifiLabelStr)], "PASS:%s</span>", pass);
wifiLabel = gtk_label_new(NULL);
gtk_label_set_markup(GTK_LABEL(wifiLabel), wifiLabelStr);
urlLabel = gtk_label_new(NULL);
gtk_label_set_markup(GTK_LABEL(urlLabel), urlLabelStr);
wifiImage = gtk_image_new_from_file("ssid.png");
urlImage = gtk_image_new_from_file("url.png");
kanadeImage = gtk_image_new_from_file("Kanade.png");
gtk_container_add(GTK_CONTAINER(window), vbox);
gtk_box_pack_start(GTK_BOX(vbox), topBox, 0, 0, 0);
gtk_box_pack_start(GTK_BOX(vbox), listTextBox, 0, 0, 0);
gtk_box_pack_start(GTK_BOX(vbox), hTextBox, 0, 0, 0);
gtk_box_pack_start(GTK_BOX(vbox), hImageBox, 0, 0, 0);
gtk_box_pack_end(GTK_BOX(vbox), kanadeImage, 0, 0, 0);
gtk_box_pack_start(GTK_BOX(topBox), pauseLabel, 0, 0, 0);
gtk_box_pack_end(GTK_BOX(topBox), quitButton, 0, 0, 0);
gtk_box_pack_start(GTK_BOX(listTextBox), userLabel, 0, 0, 0);
gtk_box_pack_start(GTK_BOX(listTextBox), songLabel, 0, 0, 0);
gtk_box_pack_start(GTK_BOX(listTextBox), commentLabel, 0, 0, 0);
gtk_box_pack_start(GTK_BOX(hTextBox), wifiLabel, 0, 0, 0);
gtk_box_pack_end(GTK_BOX(hTextBox), urlLabel, 0, 0, 0);
gtk_box_pack_start(GTK_BOX(hImageBox), wifiImage, 0, 0, 0);
gtk_box_pack_end(GTK_BOX(hImageBox), urlImage, 0, 0, 0);
gtk_widget_realize(window);
gtk_window_fullscreen((GtkWindow*)window);
g_signal_connect(window, "destroy", gtk_main_quit, NULL);
g_signal_connect_swapped(GTK_BUTTON(quitButton), "clicked", Exit, window);
gtk_widget_show_all(window);
g_timeout_add(100, (GSourceFunc)timer_handler, window);
gtk_main();
}
int
main(
int argc,
char **argv
)
{
struct addrinfo hints = { 0 };
struct addrinfo *res = NULL;
struct sockaddr_storage addr = { 0 };
socklen_t addrlen = sizeof(addr);
int conn = 0;
int yes = 1;
unsigned char *p;
unsigned long contentLength;
FILE *file = NULL;
char dir[PATH_LENGTH_MAX];
char pass[128];
char command[256];
char *result = NULL;
signal(SIGPIPE, SIG_IGN);
signal(SIGABRT, abrt_handler);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, "50000", &hints, &res);
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (-1 == sock)
{
fprintf(stderr, "Error socket()\n");
return 1;
}
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof(yes));
if (-1 == bind(sock, res->ai_addr, res->ai_addrlen))
{
fprintf(stderr, "Error bind()\n");
return 2;
}
if (-1 == listen(sock, 256))
{
fprintf(stderr, "Error listen()\n");
return 3;
}
freeaddrinfo(res);
srand((unsigned int)time(NULL));
InitFile();
InitHistory();
OpenUser();
OpenFile();
strcpy(dir, "/media/pi");
WalkDir(dir, strlen("/media/pi"));
strcpy(dir, "/home/pi/Desktop");
WalkDir(dir, strlen("/home/pi/Desktop"));
OpenBook();
OpenFavorite();
OpenHistory();
pthread_t playThread;
pthread_create(&playThread, NULL, PlayThread, NULL);
pthread_detach(playThread);
pthread_t keypadThread;
pthread_create(&keypadThread, NULL, KeyPadThread, NULL);
pthread_detach(keypadThread);
system("sh ip.sh > ip.txt");
system("sh AccessPointSSID.sh > AccessPointSSID.txt");
system("sh url.sh > url.txt");
system("sh AccessPointPass.sh > AccessPointPass.txt");
file = fopen("AccessPointPass.txt", "r");
result = fgets(pass, 64, file);
fclose(file);
if (NULL == result)
{
system("sh QRCodeAccessPointNoPass.sh > QRCodeAccessPointNoPass.txt");
system("qrencode -r QRCodeAccessPointNoPass.txt -d 400 -l H -s 7 -o ssid.png");
}
else
{
pass[strlen(pass) - 1] = 0;
sprintf(command, "sh QRCodeAccessPointWithPass.sh %s > QRCodeAccessPointWithPass.txt", pass);
system(command);
system("qrencode -r QRCodeAccessPointWithPass.txt -d 400 -l H -s 7 -o ssid.png");
}
system("qrencode -r url.txt -d 400 -l H -s 7 -o url.png");
pthread_t guiThread;
gtk_init(&argc, &argv);
pthread_create(&guiThread, NULL, GuiThread, NULL);
pthread_detach(guiThread);
//system("chromium-browser --noerrdialogs --kiosk --incognito --no-default-browser-check --no-sandbox --test-type http://localhost:50000/view.html 2> /dev/null > /dev/null &");
for(;;)
{
conn = accept(sock, (struct sockaddr*)&addr, &addrlen);
if (NULL == sockList)
{
sockList = malloc(sizeof(SockList));
sockList->sock = conn;
sockList->next = NULL;
}
else
{
SockList *p = sockList;
while(p->next != NULL)
{
p = p->next;
}
p->next = malloc(sizeof(SockList));
p = p->next;
p->sock = conn;
p->next = NULL;
}
pthread_t thread;
pthread_create(&thread, NULL, HttpThread, (void*)conn);
pthread_detach(thread);
}
}
|
kasshisatari/Kanade | omxplayer.c | <reponame>kasshisatari/Kanade
/* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <pthread.h>
#include <sys/stat.h>
#define BUF_SIZE 512
static unsigned char helloMsg[] =
{
0x6c, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6e, 0x00, 0x00, 0x00,
0x01, 0x01, 0x6f, 0x00, 0x15, 0x00, 0x00, 0x00, 0x2f, 0x6f, 0x72, 0x67, 0x2f, 0x66, 0x72, 0x65,
0x65, 0x64, 0x65, 0x73, 0x6b, 0x74, 0x6f, 0x70, 0x2f, 0x44, 0x42, 0x75, 0x73, 0x00, 0x00, 0x00,
0x06, 0x01, 0x73, 0x00, 0x14, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x66, 0x72, 0x65, 0x65,
0x64, 0x65, 0x73, 0x6b, 0x74, 0x6f, 0x70, 0x2e, 0x44, 0x42, 0x75, 0x73, 0x00, 0x00, 0x00, 0x00,
0x02, 0x01, 0x73, 0x00, 0x14, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x66, 0x72, 0x65, 0x65,
0x64, 0x65, 0x73, 0x6b, 0x74, 0x6f, 0x70, 0x2e, 0x44, 0x42, 0x75, 0x73, 0x00, 0x00, 0x00, 0x00,
0x03, 0x01, 0x73, 0x00, 0x05, 0x00, 0x00, 0x00, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00
};
static unsigned char getPosMsg[] =
{
0x6c ,0x01 ,0x00 ,0x01 ,0x31 ,0x00 ,0x00 ,0x00 ,0x01 ,0x00 ,0x00 ,0x00 ,0x90 ,0x00 ,0x00 ,0x00,
0x01 ,0x01 ,0x6f ,0x00 ,0x17 ,0x00 ,0x00 ,0x00 ,0x2f ,0x6f ,0x72 ,0x67 ,0x2f ,0x6d ,0x70 ,0x72,
0x69 ,0x73 ,0x2f ,0x4d ,0x65 ,0x64 ,0x69 ,0x61 ,0x50 ,0x6c ,0x61 ,0x79 ,0x65 ,0x72 ,0x32 ,0x00,
0x02 ,0x01 ,0x73 ,0x00 ,0x1f ,0x00 ,0x00 ,0x00 ,0x6f ,0x72 ,0x67 ,0x2e ,0x66 ,0x72 ,0x65 ,0x65,
0x64 ,0x65 ,0x73 ,0x6b ,0x74 ,0x6f ,0x70 ,0x2e ,0x44 ,0x42 ,0x75 ,0x73 ,0x2e ,0x50 ,0x72 ,0x6f,
0x70 ,0x65 ,0x72 ,0x74 ,0x69 ,0x65 ,0x73 ,0x00 ,0x03 ,0x01 ,0x73 ,0x00 ,0x03 ,0x00 ,0x00 ,0x00,
0x47 ,0x65 ,0x74 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x06 ,0x01 ,0x73 ,0x00 ,0x20 ,0x00 ,0x00 ,0x00,
0x6f ,0x72 ,0x67 ,0x2e ,0x6d ,0x70 ,0x72 ,0x69 ,0x73 ,0x2e ,0x4d ,0x65 ,0x64 ,0x69 ,0x61 ,0x50,
0x6c ,0x61 ,0x79 ,0x65 ,0x72 ,0x32 ,0x2e ,0x6f ,0x6d ,0x78 ,0x70 ,0x6c ,0x61 ,0x79 ,0x65 ,0x72,
0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x08 ,0x01 ,0x67 ,0x00 ,0x02 ,0x73 ,0x73 ,0x00,
0x1d ,0x00 ,0x00 ,0x00 ,0x6f ,0x72 ,0x67 ,0x2e ,0x6d ,0x70 ,0x72 ,0x69 ,0x73 ,0x2e ,0x4d ,0x65,
0x64 ,0x69 ,0x61 ,0x50 ,0x6c ,0x61 ,0x79 ,0x65 ,0x72 ,0x32 ,0x2e ,0x50 ,0x6c ,0x61 ,0x79 ,0x65,
0x72 ,0x00 ,0x00 ,0x00 ,0x08 ,0x00 ,0x00 ,0x00 ,0x50 ,0x6f ,0x73 ,0x69 ,0x74 ,0x69 ,0x6f ,0x6e,
0x00
};
static unsigned char stopMsg[] =
{
0x6c, 0x01, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00,
0x01, 0x01, 0x6f, 0x00, 0x17, 0x00, 0x00, 0x00, 0x2f, 0x6f, 0x72, 0x67, 0x2f, 0x6d, 0x70, 0x72,
0x69, 0x73, 0x2f, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x00,
0x02, 0x01, 0x73, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69,
0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x00, 0x00, 0x00, 0x03, 0x01, 0x73, 0x00, 0x06, 0x00, 0x00, 0x00,
0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x06, 0x01, 0x73, 0x00, 0x20, 0x00, 0x00, 0x00,
0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69, 0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x6f, 0x6d, 0x78, 0x70, 0x6c, 0x61, 0x79, 0x65, 0x72,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x01, 0x67, 0x00, 0x01, 0x69, 0x00, 0x00,
0x0f, 0x00, 0x00, 0x00
};
static unsigned char pauseMsg[] =
{
0x6c, 0x01, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00,
0x01, 0x01, 0x6f, 0x00, 0x17, 0x00, 0x00, 0x00, 0x2f, 0x6f, 0x72, 0x67, 0x2f, 0x6d, 0x70, 0x72,
0x69, 0x73, 0x2f, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x00,
0x02, 0x01, 0x73, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69,
0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x00, 0x00, 0x00, 0x03, 0x01, 0x73, 0x00, 0x06, 0x00, 0x00, 0x00,
0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x06, 0x01, 0x73, 0x00, 0x20, 0x00, 0x00, 0x00,
0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69, 0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x6f, 0x6d, 0x78, 0x70, 0x6c, 0x61, 0x79, 0x65, 0x72,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x01, 0x67, 0x00, 0x01, 0x69, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00
};
static unsigned char volUpMsg[] =
{
0x6c, 0x01, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00,
0x01, 0x01, 0x6f, 0x00, 0x17, 0x00, 0x00, 0x00, 0x2f, 0x6f, 0x72, 0x67, 0x2f, 0x6d, 0x70, 0x72,
0x69, 0x73, 0x2f, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x00,
0x02, 0x01, 0x73, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69,
0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x00, 0x00, 0x00, 0x03, 0x01, 0x73, 0x00, 0x06, 0x00, 0x00, 0x00,
0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x06, 0x01, 0x73, 0x00, 0x20, 0x00, 0x00, 0x00,
0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69, 0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x6f, 0x6d, 0x78, 0x70, 0x6c, 0x61, 0x79, 0x65, 0x72,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x01, 0x67, 0x00, 0x01, 0x69, 0x00, 0x00,
0x12, 0x00, 0x00, 0x00
};
static unsigned char volDownMsg[] =
{
0x6c, 0x01, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00,
0x01, 0x01, 0x6f, 0x00, 0x17, 0x00, 0x00, 0x00, 0x2f, 0x6f, 0x72, 0x67, 0x2f, 0x6d, 0x70, 0x72,
0x69, 0x73, 0x2f, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x00,
0x02, 0x01, 0x73, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69,
0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x00, 0x00, 0x00, 0x03, 0x01, 0x73, 0x00, 0x06, 0x00, 0x00, 0x00,
0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x06, 0x01, 0x73, 0x00, 0x20, 0x00, 0x00, 0x00,
0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69, 0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x6f, 0x6d, 0x78, 0x70, 0x6c, 0x61, 0x79, 0x65, 0x72,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x01, 0x67, 0x00, 0x01, 0x69, 0x00, 0x00,
0x11, 0x00, 0x00, 0x00
};
static unsigned char ffMsg[] =
{
0x6c, 0x01, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00,
0x01, 0x01, 0x6f, 0x00, 0x17, 0x00, 0x00, 0x00, 0x2f, 0x6f, 0x72, 0x67, 0x2f, 0x6d, 0x70, 0x72,
0x69, 0x73, 0x2f, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x00,
0x02, 0x01, 0x73, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69,
0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x00, 0x00, 0x00, 0x03, 0x01, 0x73, 0x00, 0x04, 0x00, 0x00, 0x00,
0x53, 0x65, 0x65, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x73, 0x00, 0x20, 0x00, 0x00, 0x00,
0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69, 0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x6f, 0x6d, 0x78, 0x70, 0x6c, 0x61, 0x79, 0x65, 0x72,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x01, 0x67, 0x00, 0x01, 0x78, 0x00, 0x00,
0x40, 0x4b, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x00
};
static unsigned char rwMsg[] =
{
0x6c, 0x01, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00,
0x01, 0x01, 0x6f, 0x00, 0x17, 0x00, 0x00, 0x00, 0x2f, 0x6f, 0x72, 0x67, 0x2f, 0x6d, 0x70, 0x72,
0x69, 0x73, 0x2f, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x00,
0x02, 0x01, 0x73, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69,
0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x00, 0x00, 0x00, 0x03, 0x01, 0x73, 0x00, 0x04, 0x00, 0x00, 0x00,
0x53, 0x65, 0x65, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x73, 0x00, 0x20, 0x00, 0x00, 0x00,
0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69, 0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x6f, 0x6d, 0x78, 0x70, 0x6c, 0x61, 0x79, 0x65, 0x72,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x01, 0x67, 0x00, 0x01, 0x78, 0x00, 0x00,
0xc0, 0xb4, 0xb3, 0xff, 0xff, 0xff, 0xff, 0xff
};
static unsigned char trackMsg[] =
{
0x6c, 0x01, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x97, 0x00, 0x00, 0x00, /*0x00*/
0x01, 0x01, 0x6f, 0x00, 0x17, 0x00, 0x00, 0x00, 0x2f, 0x6f, 0x72, 0x67, 0x2f, 0x6d, 0x70, 0x72, /*0x10*/
0x69, 0x73, 0x2f, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x00, /*0x20*/
0x02, 0x01, 0x73, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69, /*0x30*/
0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x50, /*0x40*/
0x6c, 0x61, 0x79, 0x65, 0x72, 0x00, 0x00, 0x00, 0x03, 0x01, 0x73, 0x00, 0x0b, 0x00, 0x00, 0x00, /*0x50*/
0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x41, 0x75, 0x64, 0x69, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, /*0x60*/
0x06, 0x01, 0x73, 0x00, 0x20, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69, /*0x70*/
0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x6f, /*0x80*/
0x6d, 0x78, 0x70, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*0x90*/
0x08, 0x01, 0x67, 0x00, 0x01, 0x69, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 /*0xa0*/
/* this(0xa8) */
/*0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 */
};
static unsigned char seekMsg[] =
{
0x6c, 0x01, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00,
0x01, 0x01, 0x6f, 0x00, 0x17, 0x00, 0x00, 0x00, 0x2f, 0x6f, 0x72, 0x67, 0x2f, 0x6d, 0x70, 0x72,
0x69, 0x73, 0x2f, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x00,
0x02, 0x01, 0x73, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69,
0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x00, 0x00, 0x00, 0x03, 0x01, 0x73, 0x00, 0x04, 0x00, 0x00, 0x00,
0x53, 0x65, 0x65, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x73, 0x00, 0x20, 0x00, 0x00, 0x00,
0x6f, 0x72, 0x67, 0x2e, 0x6d, 0x70, 0x72, 0x69, 0x73, 0x2e, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x50,
0x6c, 0x61, 0x79, 0x65, 0x72, 0x32, 0x2e, 0x6f, 0x6d, 0x78, 0x70, 0x6c, 0x61, 0x79, 0x65, 0x72,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x01, 0x67, 0x00, 0x01, 0x78, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static long volTable[21] =
{
-6000, -5700, -5400, -5100, -4800,
-4500, -4200, -3900, -3600, -3300,
-3000, -2700, -2400, -2100, -1800,
-1500, -1200, -900, -600, -300,
0
};
static long long* playTime;
static int* volume = 0;
static int sock = 0;
static unsigned char cmdIndex = 0;
static pthread_mutex_t lock;
static unsigned char audioTrackNum = 0;
static unsigned char audioTrackCurrent = 0;
static unsigned char state = 0;
char *commands[] =
{
"omxplayer --no-osd -b -o alsa ",
"omxplayer --no-osd -b -o alsa "
};
static
unsigned char *
LoadAddress(
unsigned char* buf,
unsigned short bufSize
)
{
char *head = NULL;
char *tail = NULL;
memset(buf, 0, sizeof(char)*BUF_SIZE);
/* [[[ 1. Load File ]]] */
struct stat st;
while (0 != stat("/tmp/omxplayerdbus.root", &st) && 0 != st.st_size)
{
usleep(100000);
}
FILE *file = NULL;
do
{
while (NULL == file)
{
usleep(100000);
file = fopen("/tmp/omxplayerdbus.root", "r");
}
fgets(buf, bufSize, file);
fclose(file);
}while(*buf == 0);
/* [[[ 2. Split Address ]]] */
/* [[ 2.1. Seek Head ]] */
head = buf;
while('=' != *head && *head != 0)
{
head++;
}
head++;
/* [[ 2.2. Seek Tail ]] */
tail = head;
while(',' != *tail && *tail != 0)
{
tail++;
}
*tail = '\0';
return head;
}
static
void
SendMsg(
int sock,
unsigned char *buf,
unsigned short size
)
{
write(sock, buf, size);
}
static
void
RecvMsg(
int sock,
unsigned char *buf,
unsigned short bufSize,
unsigned short size
)
{
int readSize = 0;
int sumSize = 0;
for (sumSize = 0; sumSize < size; sumSize += readSize)
{
readSize = read(sock, &(buf[sumSize]), bufSize - sumSize);
}
}
static
int
ConnectOMXPlayer(
void
)
{
int retSize = 0;
int sumSize = 0;
int srvfd = 0;
struct sockaddr_un addr = {0};
static unsigned char buf[BUF_SIZE] = {0};
/* [[[ 1. Connect UNIX Abstract Socket ]]] */
srvfd = socket(AF_UNIX, SOCK_STREAM, 0);
addr.sun_family = AF_UNIX;
addr.sun_path[0] = 0;
strcpy(&addr.sun_path[1], LoadAddress(buf, BUF_SIZE));
if (connect(
srvfd,
(struct sockaddr*)&addr,
strlen(&addr.sun_path[1]) + 3) < 0)
{
/* < Failure > */
return 0;
}
/* [[[ 2. Start Sequence ]]] */
memset(buf, 0, BUF_SIZE);
SendMsg(srvfd, buf, 1);
strcpy(buf, "AUTH EXTERNAL 30\r\n");
SendMsg(srvfd, buf, strlen(buf));
RecvMsg(srvfd, buf, BUF_SIZE, 37);
strcpy(buf, "NEGOTIATE_UNIX_FD\r\n");
SendMsg(srvfd, buf, strlen(buf));
RecvMsg(srvfd, buf, BUF_SIZE, 15);
strcpy(buf, "BEGIN\r\n");
SendMsg(srvfd, buf, strlen(buf));
SendMsg(srvfd, helloMsg, sizeof(helloMsg));
RecvMsg(srvfd, buf, BUF_SIZE, 258);
return srvfd;
}
static
unsigned char
GetPosition(
int sock,
long long *position
)
{
int retSize = 0;
long long *pos = 0;
static unsigned char buf[BUF_SIZE] = {0};
memset(buf, 0, BUF_SIZE);
SendMsg(sock, getPosMsg, sizeof(getPosMsg));
RecvMsg(sock, buf, BUF_SIZE, 72);
if (3 == buf[1])
{
/* < Error > */
return 0;
}
pos = (long long*)&(buf[0x40]);
if (*pos < 0)
{
*position = 0;
}
else
{
*position = *pos;
}
return 1;
}
static
void
Stop(
int sock
)
{
if (0 == sock)
{
return;
}
static unsigned char buf[BUF_SIZE] = {0};
SendMsg(sock, stopMsg, sizeof(stopMsg));
RecvMsg(sock, buf, BUF_SIZE, 56);
}
long long
OMXGetPosition(
void
)
{
pthread_mutex_lock(&lock);
if (0 == GetPosition(sock, playTime))
{
state = 0;
}
pthread_mutex_unlock(&lock);
return (*playTime) / 1000;
}
void
OMXFadeoutVolume(
void
)
{
static unsigned char buf[BUF_SIZE] = {0};
int i = 0;
for (i=0; i<15; ++i)
{
pthread_mutex_lock(&lock);
SendMsg(sock, volDownMsg, sizeof(volDownMsg));
RecvMsg(sock, buf, BUF_SIZE, 56);
pthread_mutex_unlock(&lock);
usleep(200000);
}
}
void
OMXStopVideo(
void
)
{
pthread_mutex_lock(&lock);
Stop(sock);
pthread_mutex_unlock(&lock);
}
void
OMXPauseVideo(
void
)
{
static unsigned char buf[BUF_SIZE] = {0};
pthread_mutex_lock(&lock);
SendMsg(sock, pauseMsg, sizeof(pauseMsg));
RecvMsg(sock, buf, BUF_SIZE, 56);
pthread_mutex_unlock(&lock);
}
void
OMXRWVideo(
void
)
{
static unsigned char buf[BUF_SIZE] = {0};
pthread_mutex_lock(&lock);
SendMsg(sock, rwMsg, sizeof(rwMsg));
RecvMsg(sock, buf, BUF_SIZE, 72);
pthread_mutex_unlock(&lock);
}
void
OMXFFVideo(
void
)
{
static unsigned char buf[BUF_SIZE] = {0};
pthread_mutex_lock(&lock);
SendMsg(sock, ffMsg, sizeof(ffMsg));
RecvMsg(sock, buf, BUF_SIZE, 72);
pthread_mutex_unlock(&lock);
}
void
OMXDownVolume(
void
)
{
static unsigned char buf[BUF_SIZE] = {0};
pthread_mutex_lock(&lock);
*volume -= 5;
if (*volume < 0)
{
*volume = 0;
pthread_mutex_unlock(&lock);
return;
}
SendMsg(sock, volDownMsg, sizeof(volDownMsg));
RecvMsg(sock, buf, BUF_SIZE, 56);
pthread_mutex_unlock(&lock);
}
void
OMXUpVolume(
void
)
{
static unsigned char buf[BUF_SIZE] = {0};
pthread_mutex_lock(&lock);
*volume += 5;
if (*volume > 100)
{
*volume = 100;
pthread_mutex_unlock(&lock);
return;
}
SendMsg(sock, volUpMsg, sizeof(volUpMsg));
RecvMsg(sock, buf, BUF_SIZE, 56);
pthread_mutex_unlock(&lock);
}
void
OMXChangeAudioTrack(
void
)
{
unsigned char cmd[128];
if (1 == audioTrackNum)
{
return;
}
audioTrackCurrent++;
if (audioTrackNum == audioTrackCurrent)
{
audioTrackCurrent = 0;
}
static unsigned char buf[BUF_SIZE] = {0};
pthread_mutex_lock(&lock);
trackMsg[0xa8] = audioTrackCurrent;
SendMsg(sock, trackMsg, sizeof(trackMsg));
RecvMsg(sock, buf, BUF_SIZE, 68);
SendMsg(sock, seekMsg, sizeof(seekMsg));
RecvMsg(sock, buf, BUF_SIZE, 72);
pthread_mutex_unlock(&lock);
}
void
OMXInitPlayer(
unsigned char audioOutput,
int* vol,
long long* time
)
{
volume = vol;
playTime = time;
if (0 == audioOutput || 1 == audioOutput)
{
cmdIndex = 0;
}
else if (2 == audioOutput)
{
cmdIndex = 1;
}
pthread_mutex_init(&lock, 0);
}
void
OMXOpenVideo( char *path, unsigned char audioTrack,
unsigned char audioTrackCount
)
{
FILE *file = NULL;
double vol = (*volume - 100) * 100;
unsigned char cmdLine[2048];
unsigned char env[1024];
strcpy(cmdLine, commands[cmdIndex]);
sprintf(&cmdLine[strlen(cmdLine)], "--vol %d ", volTable[(*volume)/5]);
sprintf(&cmdLine[strlen(cmdLine)], "-n %d ", audioTrack + 1);
sprintf(&cmdLine[strlen(cmdLine)], "\"%s\" &", path);
pthread_mutex_lock(&lock);
system(cmdLine);
sock = 0;
while(0 == sock)
{
sock = ConnectOMXPlayer();
}
audioTrackNum = audioTrackCount;
audioTrackCurrent = audioTrack;
state = 1;
pthread_mutex_unlock(&lock);
}
unsigned char
OMXIsPlayingVideo(
void
)
{
return state;
}
|
kasshisatari/Kanade | user.c | <filename>user.c
/* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include "sqlite3.h"
#include "user.h"
/* DB File Name */
#define DBNAME "user.db"
/* Table Schema */
#define SQLTABLE "CREATE TABLE [USER] ( [USERID] INTEGER NOT NULL UNIQUE, [USERNAME] TEXT NOT NULL UNIQUE, PRIMARY KEY(USERID));"
/* Insert SQL Statement */
#define SQLINSERT "INSERT INTO USER VALUES(?, ?);"
/* Get USERID SQL Statement */
#define SQLUSERID "SELECT USERID FROM USER WHERE ? = USERNAME;"
/* Get USERNAME SQL Statement */
#define SQLUSERNAME "SELECT USERNAME FROM USER WHERE ? = USERID;"
/* Get Max USERID SQL Statement */
#define SQLMAXUSERID "SELECT MAX(USERID) FROM USER;"
/* SQLite3 DB */
static sqlite3 *db = NULL;
/* Insert SQL Statement */
static sqlite3_stmt *insertStmt = NULL;
/* Get USERID SQL Statement */
static sqlite3_stmt *userIdStmt = NULL;
/* Get USERNAME SQL Statement */
static sqlite3_stmt *nameStmt = NULL;
/* Get Max USERID SQL Statement */
static sqlite3_stmt *maxUserIdStmt = NULL;
/* Max USERID */
static unsigned short maxUserId = 0;
/* Mutex */
static pthread_mutex_t lock;
/* Brief: Create User Account */
/* Pre-Condition: Callled OpenUser and LockUser Functions */
unsigned short /* User-ID */
CreateUser(
char* userName /* User-Name */
)
{
/* [[[ 0. Var ]]] */
/* Return Value for Sub-Functions */
int ret = 0;
/* [[[ 1. Insert User-Name ]]] */
/* [[ 1.1. Update Max USERID ]] */
maxUserId++;
/* [[ 1.2. Inser User-Name to DB ]] */
ret = sqlite3_bind_int(insertStmt, 1, maxUserId);
ret = sqlite3_bind_text(insertStmt, 2, userName, (int)strlen(userName), SQLITE_TRANSIENT);
ret = sqlite3_step(insertStmt);
/* [[[ 2. Check Already Exist User-Name ]]] */
if (SQLITE_CONSTRAINT == ret)
{
/* < Already Exist User-Name > */
/* [[ 2.1. Get User-ID for Already Exist User-Name ]] */
/* [ 2.1.1. Update Max USERID ] */
maxUserId--;
/* [ 2.1.2. Get User-ID for Already Exist User-Name from DB ] */
sqlite3_bind_text(userIdStmt, 1, userName, (int)strlen(userName), SQLITE_TRANSIENT);
sqlite3_step(userIdStmt);
ret = sqlite3_column_int(userIdStmt, 0);
/* [[ 2.2. Reset SQL Statements ]] */
/* [ 2.2.1. Insert SQL Statement ]*/
sqlite3_reset(insertStmt);
sqlite3_clear_bindings(insertStmt);
/* [ 2.2.2. Get USERID SQL Statement ] */
sqlite3_reset(userIdStmt);
sqlite3_clear_bindings(userIdStmt);
/* [ 2.2.3. Return USERID ] */
return (unsigned short)ret;
}
/* [[[ 3. Reset SQL Statements ]]] */
/* [[ 3.1. Insert SQL Statement ]] */
sqlite3_reset(insertStmt);
sqlite3_clear_bindings(insertStmt);
/* [[ 3.2. Return USER ID ]] */
return maxUserId;
}
/* Brief: Get User-Name */
/* Pre-Condition: Callled OpenUser and LockUser Functions */
unsigned short /* Result: 0 is Error, 1 is OK */
GetUserName(
unsigned short userId, /* User-ID */
char* userName /* User-Name */
)
{
/* [[[ 0. Var ]]] */
/* Return Value for Sub-Functions */
int ret = 0;
/* User-Name String */
const unsigned char *userNameStr = NULL;
/* [[[ 1. Get User-Name ]]] */
sqlite3_bind_int(nameStmt, 1, userId);
ret = sqlite3_step(nameStmt);
if (SQLITE_ROW == ret)
{
/* < Fount > */
/* [[ 1.1. Copy User-Name String ]] */
userNameStr = sqlite3_column_text(nameStmt, 0);
strcpy(userName, (const char*)userNameStr);
}
else
{
/* < Not Found > */
/* [[ 1.2. Reset SQL Statements ]] */
/* [ 1.2.1. Get USERNAME SQL Statement ]*/
sqlite3_reset(nameStmt);
sqlite3_clear_bindings(nameStmt);
/* [ 1.2.2. Return Error ] */
return 0;
}
/* [[[ 2. Reset SQL Statements ]]] */
/* [[ 2.1. Get USERNAME SQL Statement ]] */
sqlite3_reset(nameStmt);
sqlite3_clear_bindings(nameStmt);
/* [[ 2.2. Return OK ]] */
return 1;
}
/* Brief: Delete DB */
/* Pre-Condition: Callled OpenUser and LockUser Functions */
void
ResetUser(
void
)
{
/* [[[ 0. Var ]]] */
/* Error Message fo CREATE TABLE SQL Statement */
char *errMsg = NULL;
/* [[[ 1. Close DB ]]] */
CloseUser();
/* [[[ 2. Delete DB File ]]] */
remove(DBNAME);
/* [[[ 3. Initialize DB File ]]] */
/* [[ 3.1. Open DB File ]] */
sqlite3_open(DBNAME, &db);
/* [[ 3.2. Create Table ]]*/
if (SQLITE_OK != sqlite3_exec(db, SQLTABLE, NULL, NULL, &errMsg))
{
sqlite3_free(errMsg);
errMsg = NULL;
}
/* [[[ 4. Close DB File ]]] */
sqlite3_close(db);
}
/* Brief: Lock User DB */
/* Pre-Condition: Callled OpenUser Function */
void LockUser(
void
)
{
/* [[[ 1. Lock ]]] */
pthread_mutex_lock(&lock);
}
/* Brief: Unlock User DB */
/* Pre-Condition: Callled OpenUser Function */
void UnlockUser(
void
)
{
/* [[[ 1. Unlock ]]] */
pthread_mutex_unlock(&lock);
}
/* Brief: Open User DB */
void OpenUser(
void
)
{
/* [[[ 0. Var ]]] */
int ret = 0;
char *errMsg = NULL;
/* [[[ 1. Initialize Mutex ]]] */
pthread_mutex_init(&lock, 0);
/* [[[ 2. Check DB File Exist ]]] */
FILE *file = fopen(DBNAME, "r");
if (NULL == file)
{
/* < Not Found > */
/* [[ 2.1. Create DB File ]] */
ResetUser();
}
else
{
/* < Found > */
fclose(file);
}
/* [[[ 3. Open DB File ]]] */
sqlite3_open(DBNAME, &db);
/* [[[ 4. Prepare SQL Statements ]]] */
sqlite3_prepare_v2(db, SQLINSERT, -1, &insertStmt, NULL);
sqlite3_prepare_v2(db, SQLUSERID, -1, &userIdStmt, NULL);
sqlite3_prepare_v2(db, SQLUSERNAME, -1, &nameStmt, NULL);
sqlite3_prepare_v2(db, SQLMAXUSERID, -1, &maxUserIdStmt, NULL);
/* [[[ 5. Get Max User-ID ]]] */
/* [[ 5.1. Check Any User Accounts ]] */
ret = sqlite3_step(maxUserIdStmt);
if (SQLITE_ROW == ret)
{
/* < Found > */
/* [[ 5.1. Get Max User-ID from DB ]] */
maxUserId = (unsigned short)sqlite3_column_int(maxUserIdStmt, 0);
}
else
{
/* < Not Found > */
/* [[ 5.2. Update Max User-ID ]]*/
maxUserId = 0;
}
/* [[[ 6. Finalize SQL Statements ]]] */
/* [[ 6.1. Get Max USERID SQL Statement ]] */
sqlite3_reset(maxUserIdStmt);
sqlite3_finalize(maxUserIdStmt);
}
/* Brief: Close User DB */
/* Pre-Condition: Callled OpenUser Function */
void CloseUser(
void
)
{
/* [[[ 1. Finalize SQL Statements ]]] */
/* [[ 1.1. Insert SQL Statement ]] */
sqlite3_finalize(insertStmt);
/* [[ 1.2. Get USERID SQL Statement ]] */
sqlite3_finalize(userIdStmt);
/* [[ 1.3. Get USERNAME SQL Statement ]] */
sqlite3_finalize(nameStmt);
/* [[[ 2. Close DB ]]] */
sqlite3_close(db);
/* [[[ 3. Destroy Mutex ]]] */
pthread_mutex_destroy(&lock);
}
|
kasshisatari/Kanade | player.c | <gh_stars>1-10
/* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "define.h"
#include "vlc.h"
#include "omxplayer.h"
#include <pthread.h>
#include <string.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
pthread_mutex_t playerLock;
int vol = 0;
char playPath[PATH_LENGTH_MAX];
char playUser[USER_LENGTH_MAX];
char playComment[COMMENT_LENGTH_MAX];
int player = 1;
char*
GetSingerComment(
void
)
{
return playComment;
}
char*
GetSinger(
void
)
{
return playUser;
}
void
SetPlayingPath(
char* path
)
{
strcpy(playPath, path);
}
char*
GetPlayingPath(
void
)
{
return playPath;
}
int
GetVolume(
void
)
{
return vol;
}
long long
GetPosition(
void
)
{
if (0 == player)
{
return OMXGetPosition();
}
else
{
return VLCGetPosition();
}
}
void
FadeoutVolume(
void
)
{
if (0 == player)
{
OMXFadeoutVolume();
}
else
{
VLCFadeoutVolume();
}
}
void
StopVideo(
void
)
{
if (0 == player)
{
OMXStopVideo();
}
else
{
VLCStopVideo();
}
}
void
PauseVideo(
void
)
{
if (0 == player)
{
OMXPauseVideo();
}
else
{
VLCPauseVideo();
}
}
void
FFVideo(
void
)
{
if (0 == player)
{
OMXFFVideo();
}
else
{
VLCFFVideo();
}
}
void
RWVideo(
void
)
{
if (0 == player)
{
OMXRWVideo();
}
else
{
VLCRWVideo();
}
}
void
DownVolume(
void
)
{
if (0 == player)
{
OMXDownVolume();
}
else
{
VLCDownVolume();
}
}
void
UpVolume(
void
)
{
if (0 == player)
{
OMXUpVolume();
}
else
{
VLCUpVolume();
}
}
void
ChangeAudioTrack(
void
)
{
if (0 == player)
{
OMXChangeAudioTrack();
}
else
{
VLCChangeAudioTrack();
}
}
void
InitPlayer(
unsigned char audioOutput,
long long* time
)
{
pthread_mutex_init(&playerLock, 0);
OMXInitPlayer(audioOutput, &vol, time);
VLCInitPlayer(audioOutput, &vol, time);
}
void
LockPlayer(
void
)
{
pthread_mutex_lock(&playerLock);
}
void
UnlockPlayer(
void
)
{
pthread_mutex_unlock(&playerLock);
}
void
OpenVideo(
char *path,
unsigned char audioTrack
)
{
unsigned char audioTrackCount = 0;
AVFormatContext* formatContext = NULL;
int codecid = 0;
int width = 0;
int height = 0;
if (0 != avformat_open_input(&formatContext, path, NULL, NULL))
{
// < Can not open >
return;
}
if (0 > avformat_find_stream_info(formatContext, NULL))
{
// < Can not read stream >
return;
}
for(int i=0; i<(int)formatContext->nb_streams; ++i)
{
if (AVMEDIA_TYPE_VIDEO == formatContext->streams[i]->codecpar->codec_type)
{
// < Video >
codecid = formatContext->streams[i]->codecpar->codec_id;
width = formatContext->streams[i]->codecpar->width;
height = formatContext->streams[i]->codecpar->height;
}
else if (AVMEDIA_TYPE_AUDIO == formatContext->streams[i]->codecpar->codec_type)
{
// < Audio >
audioTrackCount++;
}
}
avformat_close_input(&formatContext);
#if 1 // Disable OMXPlayer
if (27 == codecid && width <= 1920 && height <= 1080)
{
player = 0;
OMXOpenVideo(path, audioTrack, audioTrackCount);
}
else
{
player = 1;
VLCOpenVideo(path, audioTrack);
}
#else
player = 1;
VLCOpenVideo(path, audioTrack);
#endif
}
unsigned char
IsPlayingVideo(
void
)
{
if (0 == player)
{
return OMXIsPlayingVideo();
}
else
{
return VLCIsPlayingVideo();
}
}
|
kasshisatari/Kanade | file.c | <reponame>kasshisatari/Kanade
/* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <pthread.h>
#include <stdlib.h>
#include "sqlite3.h"
#include "define.h"
#include "file.h"
#define DBNAME ":memory:"
#define SQLTABLE "CREATE TABLE [FILE] ([FILEID] INTEGER NOT NULL UNIQUE,[PATH] TEXT NOT NULL UNIQUE,[NAME] TEXT NOT NULL,[SIZE] INTEGER NOT NULL,[MODIFYTIME] TEXT NOT NULL,PRIMARY KEY(FILEID));"
#define SQLINSERT "INSERT INTO FILE VALUES(?, ?, ?, ?, ?);"
#define SQLDETAIL "SELECT PATH, MODIFYTIME, SIZE FROM FILE WHERE FILEID = ?;"
#define SQLPATH "SELECT PATH FROM FILE WHERE FILEID = ?;"
#define SQLMAXID "SELECT MAX(FILEID) FROM FILE;"
#define SQLTRANSACTION "BEGIN TRANSACTION;"
#define SQLRANDOM "SELECT FILEID FROM FILE ORDER BY RANDOM();"
static pthread_mutex_t lock;
static sqlite3 *db = NULL;
static sqlite3_stmt *insertStmt = NULL;
static sqlite3_stmt *detailStmt = NULL;
static sqlite3_stmt *maxIdStmt = NULL;
static sqlite3_stmt *pathStmt = NULL;
static sqlite3_stmt *randomStmt = NULL;
static unsigned long maxFileId = 0;
void
AddFile(
char* path /* file path */
)
{
int ret = 0;
char timestamp[FILE_LENGTH_MAX];
unsigned long size = 0;
char *p = path;
char *name = path;
struct stat st = { 0 };
if (0 != stat(path, &st))
{
strcpy(timestamp, "2019/01/01 00:00:00");
}
else
{
size = st.st_size;
strftime(timestamp, sizeof(timestamp), "%Y/%m/%d %H:%M:%S", localtime(&(st.st_mtime)));
}
maxFileId++;
sqlite3_bind_int(insertStmt, 1, maxFileId);
sqlite3_bind_text(insertStmt, 2, path, strlen(path), SQLITE_TRANSIENT);
while (0x00 != *p)
{
if ('/' == *p)
{
name = p + 1;
}
p++;
}
sqlite3_bind_text(insertStmt, 3, name, strlen(name), SQLITE_TRANSIENT);
sqlite3_bind_int(insertStmt, 4, size);
sqlite3_bind_text(insertStmt, 5, timestamp, strlen(timestamp), SQLITE_TRANSIENT);
ret = sqlite3_step(insertStmt);
if (SQLITE_CONSTRAINT == ret)
{
maxFileId--;
}
sqlite3_reset(insertStmt);
sqlite3_clear_bindings(insertStmt);
}
static
char*
SkipSpace(char *str)
{
while (0x00 != *str && 0x20 == *str)
{
/* < SPACE >*/
str++;
}
return str;
}
static
char*
CopyKeyword(char *dst, char *src)
{
*dst = '%';
dst++;
while (0x00 != *src && 0x20 != *src)
{
*dst = *src;
++dst;
++src;
}
*dst = '%';
dst++;
*dst = 0x00;
return src;
}
static
char*
CopyString(char *dst, char *src)
{
while (0x00 != *src)
{
*dst = *src;
++dst;
++src;
}
return dst;
}
static
unsigned char
MakeSQLForList(
char* search,
char* countSql,
char* resultSql,
char keyword[KEYWORD_MAX][FILE_LENGTH_MAX],
unsigned char sort,
unsigned long pageNo
)
{
unsigned char hasKeyword = 0;
char *p = countSql;
char *q = resultSql;
unsigned char keyIndex = 0;
p = CopyString(p, "SELECT COUNT(FILEID) FROM FILE ");
q = CopyString(q, "SELECT FILEID, PATH FROM FILE ");
while (0x00 != *search)
{
search = SkipSpace(search);
if (0x00 == *search)
{
break;
}
/* < Not SPACE > */
if (0 == hasKeyword)
{
p = CopyString(p, "WHERE PATH LIKE ? ");
q = CopyString(q, "WHERE PATH LIKE ? ");
hasKeyword = 1;
}
else
{
p = CopyString(p, "AND PATH LIKE ? ");
q = CopyString(q, "AND PATH LIKE ? ");
}
search = CopyKeyword((char*)&(keyword[keyIndex]), search);
keyIndex++;
}
q = CopyString(q, "ORDER BY ");
if (0 == sort)
{
q = CopyString(q, "NAME ASC LIMIT ");
}
else
{
q = CopyString(q, "MODIFYTIME DESC LIMIT ");
}
sprintf(q, "%d OFFSET %d", PAGERECORDS, PAGERECORDS * (pageNo - 1));
return keyIndex;
}
static
unsigned short
CopyPath(
char *dst,
const unsigned char *src
)
{
short delimiter = -1;
unsigned short count = 0;
while (0x00 != *src)
{
*dst = *src;
if ('/' == *src)
{
delimiter = count;
}
dst++;
src++;
count++;
}
*dst = 0x00;
return delimiter + 1;
}
static
unsigned long
GetPageNum(
unsigned long records
)
{
if (records % PAGERECORDS)
{
return records / PAGERECORDS + 1;
}
else
{
return records / PAGERECORDS;
}
}
unsigned long /* records */
GetFileList(
char* keyword, /* search keyword */
unsigned long pageNo, /* page No. */
unsigned char sort, /* sort kind */
unsigned long* fileIdList, /* file id list */
char* filePathList, /* file path list */
unsigned short *offsetList, /* file name offset list */
unsigned char* recordsInPage, /* records in page */
unsigned long* pageNumber
)
{
int keyIndex = 0;
char countSql[PATH_LENGTH_MAX] = { 0 };
char resultSql[PATH_LENGTH_MAX] = { 0 };
char keywords[KEYWORD_MAX][FILE_LENGTH_MAX];
sqlite3_stmt *countStmt = NULL;
sqlite3_stmt *resultStmt = NULL;
int ret = 0;
unsigned char recIndex = 0;
unsigned long records = 0;
*pageNumber = 0;
keyIndex = MakeSQLForList(keyword, countSql, resultSql, keywords, sort, pageNo);
sqlite3_prepare_v2(db, countSql, -1, &countStmt, NULL);
sqlite3_prepare_v2(db, resultSql, -1, &resultStmt, NULL);
for (int i = 0; i < keyIndex; ++i)
{
sqlite3_bind_text(countStmt, i + 1, keywords[i], strlen(keywords[i]), SQLITE_TRANSIENT);
sqlite3_bind_text(resultStmt, i + 1, keywords[i], strlen(keywords[i]), SQLITE_TRANSIENT);
}
ret = sqlite3_step(countStmt);
if (SQLITE_ROW == ret)
{
records = sqlite3_column_int(countStmt, 0);
}
if (0 == records)
{
*recordsInPage = 0;
*pageNumber = 0;
}
else
{
*pageNumber = records / PAGERECORDS;
if (0 != records % PAGERECORDS)
{
*pageNumber = *pageNumber + 1;
}
ret = sqlite3_step(resultStmt);
while (SQLITE_ROW == ret)
{
fileIdList[recIndex] = sqlite3_column_int(resultStmt, 0);
const unsigned char *p = sqlite3_column_text(resultStmt, 1);
offsetList[recIndex] = CopyPath(&(filePathList[recIndex * PATH_LENGTH_MAX]), p);
recIndex++;
ret = sqlite3_step(resultStmt);
}
}
*recordsInPage = recIndex;
sqlite3_reset(countStmt);
sqlite3_reset(resultStmt);
sqlite3_clear_bindings(countStmt);
sqlite3_clear_bindings(resultStmt);
sqlite3_finalize(countStmt);
sqlite3_finalize(resultStmt);
return records;
}
void
GetFilePath(
unsigned long fileId,
char* path
)
{
const unsigned char *p = NULL;
int ret = 0;
sqlite3_bind_int(pathStmt, 1, fileId);
ret = sqlite3_step(pathStmt);
if (SQLITE_ROW == ret)
{
p = sqlite3_column_text(pathStmt, 0);
strcpy(path, (const char*)p);
}
else
{
*path = 0;
}
sqlite3_reset(pathStmt);
sqlite3_clear_bindings(pathStmt);
}
long /* file size */
GetFileDetail(
unsigned long fileId, /* file id */
char* path, /* file path */
char* modifyTime /* modify time */
)
{
const unsigned char *p = NULL;
int ret = 0;
long size = -1;
sqlite3_bind_int(detailStmt, 1, fileId);
ret = sqlite3_step(detailStmt);
if (SQLITE_ROW == ret)
{
p = sqlite3_column_text(detailStmt, 0);
strcpy(path, (const char*)p);
p = sqlite3_column_text(detailStmt, 1);
strcpy(modifyTime, (const char*)p);
size = sqlite3_column_int(detailStmt, 2);
}
else
{
sqlite3_reset(detailStmt);
sqlite3_clear_bindings(detailStmt);
return -1;
}
sqlite3_reset(detailStmt);
sqlite3_clear_bindings(detailStmt);
return size;
}
void
InitFile(
void
)
{
pthread_mutex_init(&lock, 0);
}
void
OpenFile(
void
)
{
char *errMsg = NULL;
int ret = 0;
system("rm -fr t/*");
sqlite3_open(DBNAME, &db);
if (SQLITE_OK != sqlite3_exec(db, SQLTABLE, NULL, NULL, &errMsg))
{
sqlite3_free(errMsg);
errMsg = NULL;
}
sqlite3_prepare_v2(db, SQLINSERT, -1, &insertStmt, NULL);
sqlite3_prepare_v2(db, SQLDETAIL, -1, &detailStmt, NULL);
sqlite3_prepare_v2(db, SQLMAXID, -1, &maxIdStmt, NULL);
sqlite3_prepare_v2(db, SQLPATH, -1, &pathStmt, NULL);
sqlite3_prepare_v2(db, SQLRANDOM, -1, &randomStmt, NULL);
ret = sqlite3_step(maxIdStmt);
if (SQLITE_ROW == ret)
{
maxFileId = sqlite3_column_int(maxIdStmt, 0);
}
else
{
maxFileId = 0;
}
sqlite3_reset(maxIdStmt);
sqlite3_finalize(maxIdStmt);
}
void
CloseFile(
void
)
{
sqlite3_finalize(insertStmt);
sqlite3_finalize(detailStmt);
sqlite3_finalize(pathStmt);
sqlite3_finalize(randomStmt);
sqlite3_close(db);
}
void
ResetFile(
void
)
{
CloseFile();
}
void
LockFile(
void
)
{
pthread_mutex_lock(&lock);
}
void
UnlockFile(
void
)
{
pthread_mutex_unlock(&lock);
}
unsigned long
GetFileCount(
void
)
{
return maxFileId;
}
unsigned long
GetFileRandomId(
void
)
{
static unsigned long prevMaxFileId = 0;
static unsigned long* list = NULL;
static unsigned long count = 0;
unsigned long fileId = 0;
int ret = 0;
if (prevMaxFileId == maxFileId)
{
fileId = list[count];
count++;
if (prevMaxFileId <= count)
{
count = 0;
}
return fileId;
}
else
{
if (NULL != list)
{
free(list);
}
list = (unsigned long*)malloc(sizeof(unsigned long) * maxFileId);
count = 0;
prevMaxFileId = maxFileId;
ret = sqlite3_step(randomStmt);
while (SQLITE_ROW == ret)
{
list[count] = sqlite3_column_int(randomStmt, 0);
count++;
ret = sqlite3_step(randomStmt);
}
count = 1;
sqlite3_reset(randomStmt);
return list[0];
}
}
|
kasshisatari/Kanade | book.c | /* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include "sqlite3.h"
#include "define.h"
#include "book.h"
#define DBNAME ":memory:"
#define SQLTABLE "CREATE TABLE [BOOK] ([BOOKID] INTEGER NOT NULL UNIQUE,[USERID] INTEGER,[PATH] TEXT,[COMMENT] TEXT,[DURATION] INTEGER,[AUDIOTRACK] INTEGER,[POSITION] INTEGER NOT NULL UNIQUE,[PUBLIC] INTEGER NOT NULL,[VALID] INTEGER NOT NULL,PRIMARY KEY(BOOKID));"
#define SQLINSERT "INSERT INTO BOOK VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);"
#define SQLDELETE "DELETE FROM BOOK WHERE BOOKID = ?;"
#define SQLUPDATE "UPDATE BOOK SET PATH = ?, COMMENT = ?, DURATION = ?, AUDIOTRACK = ?, PUBLIC = ? WHERE BOOKID = ?;"
#define SQLUPCHECK "SELECT MIN(BOOK.POSITION), BOOKID, ORG.POSITION FROM BOOK, (SELECT POSITION FROM BOOK WHERE BOOKID = ?) as ORG WHERE ORG.POSITION < BOOK.POSITION;"
#define SQLDOWNCHECK "SELECT MAX(BOOK.POSITION), BOOKID, ORG.POSITION FROM BOOK, (SELECT POSITION FROM BOOK WHERE BOOKID = ?) as ORG WHERE ORG.POSITION > BOOK.POSITION;"
#define SQLMOVE "UPDATE BOOK SET POSITION = ? WHERE BOOKID = ?;"
#define SQLLIST "SELECT BOOKID, USERID, PATH, COMMENT, DURATION, PUBLIC, VALID FROM BOOK ORDER BY POSITION ASC"
#define SQLHAS "SELECT COUNT(BOOKID) FROM BOOK WHERE PATH = ?;"
#define SQLOPEN "SELECT MAX(BOOKID), MAX(POSITION), MIN(POSITION), COUNT(BOOKID) FROM BOOK;"
#define SQLCHANGE "SELECT CHANGES();"
#define SQLPATH "SELECT PATH FROM BOOK WHERE BOOKID = ?;"
#define SQLAUDIO "SELECT AUDIOTRACK FROM BOOK WHERE BOOKID = ?;"
static pthread_mutex_t lock;
static pthread_mutex_t latest;
static sqlite3 *db = NULL;
static sqlite3_stmt *insertStmt = NULL;
static sqlite3_stmt *deleteStmt = NULL;
static sqlite3_stmt *updateStmt = NULL;
static sqlite3_stmt *moveUpCheckStmt = NULL;
static sqlite3_stmt *moveDownCheckStmt = NULL;
static sqlite3_stmt *moveStmt = NULL;
static sqlite3_stmt *listStmt = NULL;
static sqlite3_stmt *hasStmt = NULL;
static sqlite3_stmt *openStmt = NULL;
static sqlite3_stmt *changeStmt = NULL;
static sqlite3_stmt *pathStmt = NULL;
static sqlite3_stmt *audioStmt = NULL;
static unsigned long maxBookId = 0;
static long minPos = 0;
static long maxPos = 0;
static unsigned short count = 0;
unsigned long latestBookId = 0;
char latestFile[PATH_LENGTH_MAX];
char latestComment[COMMENT_LENGTH_MAX];
unsigned short latestUserId = 0;
unsigned char latestVisible = 0;
unsigned char /* records */
GetBookList(
unsigned long* bookIdList,
unsigned short* userIdList,
char* filePathList,
char* commentList,
unsigned long* durationList
)
{
int ret = sqlite3_step(listStmt);
int recIndex = 0;
int valid = 0;
int visible = 0;
const unsigned char *p = NULL;
while (SQLITE_ROW == ret)
{
bookIdList[recIndex] = sqlite3_column_int(listStmt, 0);
valid = sqlite3_column_int(listStmt, 6);
if (1 == valid)
{
userIdList[recIndex] = (unsigned short)sqlite3_column_int(listStmt, 1);
visible = sqlite3_column_int(listStmt, 5);
if (1 == visible)
{
p = sqlite3_column_text(listStmt, 2);
strcpy((filePathList + PATH_LENGTH_MAX * recIndex), (const char*)p);
}
else
{
strcpy((filePathList + PATH_LENGTH_MAX * recIndex), "Secret");
}
p = sqlite3_column_text(listStmt, 3);
strcpy((commentList + COMMENT_LENGTH_MAX * recIndex), (const char*)p);
durationList[recIndex] = sqlite3_column_int(listStmt, 4);
}
else
{
userIdList[recIndex] = 0;
strcpy((filePathList + PATH_LENGTH_MAX * recIndex), "Break");
*(commentList + COMMENT_LENGTH_MAX * recIndex) = 0x00;
durationList[recIndex] = 0;
}
recIndex++;
ret = sqlite3_step(listStmt);
}
sqlite3_reset(listStmt);
return (unsigned char)recIndex;
}
unsigned long /* Book ID */
AddBook(
unsigned short userId,
char* path,
char* comment,
unsigned long duration,
unsigned char audioTrack,
unsigned char visible
)
{
if (count >= PAGERECORDS)
{
return 0;
}
count++;
maxBookId++;
maxPos++;
sqlite3_bind_int(insertStmt, 1, maxBookId);
sqlite3_bind_int(insertStmt, 2, userId);
sqlite3_bind_text(insertStmt, 3, path, strlen(path), SQLITE_TRANSIENT);
sqlite3_bind_text(insertStmt, 4, comment, strlen(comment), SQLITE_TRANSIENT);
sqlite3_bind_int(insertStmt, 5, duration);
sqlite3_bind_int(insertStmt, 6, audioTrack);
sqlite3_bind_int(insertStmt, 7, maxPos);
sqlite3_bind_int(insertStmt, 8, visible);
sqlite3_bind_int(insertStmt, 9, 1);
sqlite3_step(insertStmt);
sqlite3_reset(insertStmt);
sqlite3_clear_bindings(insertStmt);
pthread_mutex_lock(&latest);
latestBookId = maxBookId;
latestUserId = userId;
strcpy(latestComment, comment);
strcpy(latestFile, path);
latestVisible = visible;
pthread_mutex_unlock(&latest);
return maxBookId;
}
unsigned long /* Book ID */
InsertBook(
unsigned short userId,
char* path,
char* comment,
unsigned long duration,
unsigned char audioTrack,
unsigned char visible
)
{
if (count >= PAGERECORDS)
{
return 0;
}
count++;
maxBookId++;
minPos--;
sqlite3_bind_int(insertStmt, 1, maxBookId);
sqlite3_bind_int(insertStmt, 2, userId);
sqlite3_bind_text(insertStmt, 3, path, strlen(path), SQLITE_TRANSIENT);
sqlite3_bind_text(insertStmt, 4, comment, strlen(comment), SQLITE_TRANSIENT);
sqlite3_bind_int(insertStmt, 5, duration);
sqlite3_bind_int(insertStmt, 6, audioTrack);
sqlite3_bind_int(insertStmt, 7, minPos);
sqlite3_bind_int(insertStmt, 8, visible);
sqlite3_bind_int(insertStmt, 9, 1);
sqlite3_step(insertStmt);
sqlite3_reset(insertStmt);
sqlite3_clear_bindings(insertStmt);
pthread_mutex_lock(&latest);
latestBookId = maxBookId;
latestUserId = userId;
strcpy(latestComment, comment);
strcpy(latestFile, path);
latestVisible = visible;
pthread_mutex_unlock(&latest);
return maxBookId;
}
unsigned long /* Book ID */
AddBreak(
void
)
{
if (count >= PAGERECORDS)
{
return 0;
}
count++;
maxBookId++;
maxPos++;
sqlite3_bind_int(insertStmt, 1, maxBookId);
sqlite3_bind_int(insertStmt, 2, 0);
sqlite3_bind_text(insertStmt, 3, "", 0, SQLITE_TRANSIENT);
sqlite3_bind_text(insertStmt, 4, "", 0, SQLITE_TRANSIENT);
sqlite3_bind_int(insertStmt, 5, 0);
sqlite3_bind_int(insertStmt, 6, 0);
sqlite3_bind_int(insertStmt, 7, maxPos);
sqlite3_bind_int(insertStmt, 8, 1);
sqlite3_bind_int(insertStmt, 9, 0);
sqlite3_step(insertStmt);
sqlite3_reset(insertStmt);
sqlite3_clear_bindings(insertStmt);
return maxBookId;
}
unsigned long /* Book ID */
InsertBreak(
void
)
{
if (count >= PAGERECORDS)
{
return 0;
}
count++;
maxBookId++;
minPos--;
sqlite3_bind_int(insertStmt, 1, maxBookId);
sqlite3_bind_int(insertStmt, 2, 0);
sqlite3_bind_text(insertStmt, 3, "", 0, SQLITE_TRANSIENT);
sqlite3_bind_text(insertStmt, 4, "", 0, SQLITE_TRANSIENT);
sqlite3_bind_int(insertStmt, 5, 0);
sqlite3_bind_int(insertStmt, 6, 0);
sqlite3_bind_int(insertStmt, 7, minPos);
sqlite3_bind_int(insertStmt, 8, 1);
sqlite3_bind_int(insertStmt, 9, 0);
sqlite3_step(insertStmt);
sqlite3_reset(insertStmt);
sqlite3_clear_bindings(insertStmt);
return maxBookId;
}
unsigned long
DeleteBook(
unsigned long bookId
)
{
int ret = 0;
unsigned char changed = 0;
sqlite3_bind_int(deleteStmt, 1, bookId);
sqlite3_step(deleteStmt);
sqlite3_reset(deleteStmt);
sqlite3_clear_bindings(deleteStmt);
ret = sqlite3_step(openStmt);
if (SQLITE_ROW == ret)
{
count = (unsigned char)sqlite3_column_int(openStmt, 3);
}
else
{
count = 0;
}
sqlite3_reset(openStmt);
sqlite3_step(changeStmt);
changed = (unsigned char)sqlite3_column_int(changeStmt, 0);
sqlite3_reset(changeStmt);
if (1 == changed)
{
return bookId;
}
else
{
return 0;
}
}
unsigned long /* Book ID */
MoveBook(
unsigned long bookId,
unsigned char dir
)
{
long srcPos = 0;
long dstPos = 0;
unsigned long dstId = 0;
if (0 == dir)
{
// < Up >
sqlite3_bind_int(moveUpCheckStmt, 1, bookId);
sqlite3_step(moveUpCheckStmt);
dstPos = sqlite3_column_int(moveUpCheckStmt, 0);
dstId = sqlite3_column_int(moveUpCheckStmt, 1);
srcPos = sqlite3_column_int(moveUpCheckStmt, 2);
sqlite3_reset(moveUpCheckStmt);
sqlite3_clear_bindings(moveUpCheckStmt);
if (0 == dstId)
{
// < Not Found >
return 0;
}
}
else
{
// < Down >
sqlite3_bind_int(moveDownCheckStmt, 1, bookId);
sqlite3_step(moveDownCheckStmt);
dstPos = sqlite3_column_int(moveDownCheckStmt, 0);
dstId = sqlite3_column_int(moveDownCheckStmt, 1);
srcPos = sqlite3_column_int(moveDownCheckStmt, 2);
sqlite3_reset(moveDownCheckStmt);
sqlite3_clear_bindings(moveDownCheckStmt);
if (0 == dstId)
{
// < Not Found >
return 0;
}
}
sqlite3_bind_int(moveStmt, 1, 0);
sqlite3_bind_int(moveStmt, 2, bookId);
sqlite3_step(moveStmt);
sqlite3_reset(moveStmt);
sqlite3_clear_bindings(moveStmt);
sqlite3_bind_int(moveStmt, 1, srcPos);
sqlite3_bind_int(moveStmt, 2, dstId);
sqlite3_step(moveStmt);
sqlite3_reset(moveStmt);
sqlite3_clear_bindings(moveStmt);
sqlite3_bind_int(moveStmt, 1, dstPos);
sqlite3_bind_int(moveStmt, 2, bookId);
sqlite3_step(moveStmt);
sqlite3_reset(moveStmt);
sqlite3_clear_bindings(moveStmt);
return bookId;
}
unsigned char /* Exist */
HasBook(
char* path
)
{
unsigned char ret = 0;
sqlite3_bind_text(hasStmt, 1, path, strlen(path), SQLITE_TRANSIENT);
sqlite3_step(hasStmt);
ret = (unsigned char)sqlite3_column_int(hasStmt, 0);
sqlite3_reset(hasStmt);
sqlite3_clear_bindings(hasStmt);
return ret;
}
unsigned long /* Book ID */
ModifyBook(
unsigned long bookId,
char* path,
char* comment,
unsigned long duration,
unsigned char audioTrack,
unsigned char visible
)
{
unsigned char changed = 0;
sqlite3_bind_text(updateStmt, 1, path, strlen(path), SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 2, comment, strlen(comment), SQLITE_TRANSIENT);
sqlite3_bind_int(updateStmt, 3, duration);
sqlite3_bind_int(updateStmt, 4, audioTrack);
sqlite3_bind_int(updateStmt, 5, visible);
sqlite3_bind_int(updateStmt, 6, bookId);
sqlite3_step(updateStmt);
sqlite3_reset(updateStmt);
sqlite3_clear_bindings(updateStmt);
sqlite3_step(changeStmt);
changed = (unsigned char)sqlite3_column_int(changeStmt, 0);
sqlite3_reset(changeStmt);
if (1 == changed)
{
return bookId;
}
else
{
return 0;
}
}
void
OpenBook(
void
)
{
char *errMsg = NULL;
int ret = 0;
pthread_mutex_init(&lock, 0);
pthread_mutex_init(&latest, 0);
sqlite3_open(DBNAME, &db);
if (SQLITE_OK != sqlite3_exec(db, SQLTABLE, NULL, NULL, &errMsg))
{
sqlite3_free(errMsg);
errMsg = NULL;
}
sqlite3_prepare_v2(db, SQLINSERT, -1, &insertStmt, NULL);
sqlite3_prepare_v2(db, SQLDELETE, -1, &deleteStmt, NULL);
sqlite3_prepare_v2(db, SQLUPDATE, -1, &updateStmt, NULL);
sqlite3_prepare_v2(db, SQLMOVE, -1, &moveStmt, NULL);
sqlite3_prepare_v2(db, SQLUPCHECK, -1, &moveUpCheckStmt, NULL);
sqlite3_prepare_v2(db, SQLDOWNCHECK, -1, &moveDownCheckStmt, NULL);
sqlite3_prepare_v2(db, SQLLIST, -1, &listStmt, NULL);
sqlite3_prepare_v2(db, SQLHAS, -1, &hasStmt, NULL);
sqlite3_prepare_v2(db, SQLOPEN, -1, &openStmt, NULL);
sqlite3_prepare_v2(db, SQLCHANGE, -1, &changeStmt, NULL);
sqlite3_prepare_v2(db, SQLPATH, -1, &pathStmt, NULL);
sqlite3_prepare_v2(db, SQLAUDIO, -1, &audioStmt, NULL);
ret = sqlite3_step(openStmt);
if (SQLITE_ROW == ret)
{
maxBookId = (unsigned long)sqlite3_column_int(openStmt, 0);
maxPos = sqlite3_column_int(openStmt, 1);
if (maxPos < 0)
{
maxPos = 0;
}
minPos = sqlite3_column_int(openStmt, 2);
if (minPos > 0)
{
minPos = 0;
}
count = (unsigned char)sqlite3_column_int(openStmt, 3);
}
else
{
maxBookId = 0;
maxPos = 0;
minPos = 0;
count = 0;
}
sqlite3_reset(openStmt);
}
void
CloseBook(
void
)
{
sqlite3_finalize(insertStmt);
sqlite3_finalize(deleteStmt);
sqlite3_finalize(updateStmt);
sqlite3_finalize(moveStmt);
sqlite3_finalize(moveUpCheckStmt);
sqlite3_finalize(moveDownCheckStmt);
sqlite3_finalize(listStmt);
sqlite3_finalize(hasStmt);
sqlite3_finalize(openStmt);
sqlite3_finalize(changeStmt);
sqlite3_finalize(pathStmt);
sqlite3_finalize(audioStmt);
sqlite3_close(db);
pthread_mutex_destroy(&lock);
}
void
ResetBook(
void
)
{
CloseBook();
}
void
LockBook(
void
)
{
pthread_mutex_lock(&lock);
}
void
UnlockBook(
void
)
{
pthread_mutex_unlock(&lock);
pthread_mutex_unlock(&latest);
}
void
GetBookPath(
unsigned long bookId,
char* path
)
{
const unsigned char *p = NULL;
sqlite3_bind_int(pathStmt, 1, bookId);
sqlite3_step(pathStmt);
p = sqlite3_column_text(pathStmt, 0);
strcpy(path, (const char*)p);
sqlite3_reset(pathStmt);
sqlite3_clear_bindings(pathStmt);
}
unsigned char
GetBookAudio(
unsigned long bookId
)
{
unsigned char audio = 0;
sqlite3_bind_int(audioStmt, 1, bookId);
sqlite3_step(audioStmt);
audio = sqlite3_column_int(audioStmt, 0);
sqlite3_reset(audioStmt);
sqlite3_clear_bindings(audioStmt);
return audio;
}
void
GetLatestBook(
unsigned long *bookId,
unsigned short *userId,
char *file,
char *comment,
unsigned char *visible
)
{
pthread_mutex_lock(&latest);
*bookId = latestBookId;
*userId = latestUserId;
strcpy(comment, latestComment);
strcpy(file, latestFile);
*visible = latestVisible;
pthread_mutex_unlock(&latest);
}
|
kasshisatari/Kanade | vlc.c | /* Copyright 2020 oscillo
Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files(the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions :
The above copyright notice and this permission
notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <vlc/vlc.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
static long long* playTime;
static int* volume = 0;
static int sock = 0;
static
unsigned char /* Reply */
SendCmd(
unsigned char cmd
)
{
unsigned char buf;
int res = 0;
int recvSize = 0;
if (0 == sock)
{
return 0;
}
res = write(sock, &cmd, 1);
if (res < 0)
{
close(sock);
sock = 0;
return 0;
}
recvSize = read(sock, &buf, 1);
if (-1 == recvSize)
{
close(sock);
sock = 0;
}
return buf;
}
long long
VLCGetPosition(
void
)
{
unsigned char c = 'A';
long long playTime;
int res = 0;
int recvSize = 0;
if (0 == sock)
{
return 0;
}
res = write(sock, &c, 1);
if (res < 0)
{
close(sock);
sock = 0;
return 0;
}
recvSize = read(sock, &playTime, sizeof(long long));
if (-1 == recvSize)
{
close(sock);
sock = 0;
return 0;
}
return playTime;
}
void
VLCFadeoutVolume(
void
)
{
SendCmd('B');
}
void
VLCStopVideo(
void
)
{
SendCmd('C');
}
void
VLCPauseVideo(
void
)
{
SendCmd('D');
}
void
VLCRWVideo(
void
)
{
SendCmd('E');
}
void
VLCFFVideo(
void
)
{
SendCmd('F');
}
void
VLCDownVolume(
void
)
{
*volume -= 5;
if (*volume < 0)
{
*volume = 0;
return;
}
SendCmd('G');
}
void
VLCUpVolume(
void
)
{
*volume += 5;
if (100 < *volume)
{
*volume = 100;
return;
}
SendCmd('H');
}
void
VLCChangeAudioTrack(
void
)
{
SendCmd('I');
}
void
VLCInitPlayer(
unsigned char audioOutput,
int* vol,
long long* time
)
{
volume = vol;
playTime = time;
}
void
VLCOpenVideo(
char *path,
unsigned char audioTrack
)
{
unsigned char cmdLine[1024];
sprintf(cmdLine, "./vlcwrapper \"%s\" ", path);
sprintf(&cmdLine[strlen(cmdLine)], "%d ", audioTrack);
sprintf(&cmdLine[strlen(cmdLine)], "%d &", *volume);
system(cmdLine);
sock = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un sa = {0};
sa.sun_family = AF_UNIX;
strcpy(sa.sun_path, "/tmp/vlcwrapper");
while (0 != connect(sock, (struct sockaddr*)&sa, sizeof(struct sockaddr_un)));
}
unsigned char
VLCIsPlayingVideo(
void
)
{
unsigned char buf = SendCmd('J');
if ('0' == buf)
{
return 0;
}
else if ('1' == buf)
{
return 1;
}
}
|
schwehr/gdal-autotest2 | cpp/util/cpl_cstringlist.h | <reponame>schwehr/gdal-autotest2
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_CPL_CSTRINGLIST_H_
#define THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_CPL_CSTRINGLIST_H_
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace autotest2 {
typedef std::unique_ptr<char *, std::function<void(char **)>> StringListPtr;
// C String List (CSL) helpers.
std::vector<string> CslToVector(const char *const *string_list);
// Caller must delete the returned result with CSLDestroy.
char **VectorToCsl(const std::vector<string> &vs);
} // namespace autotest2
#endif // THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_CPL_CSTRINGLIST_H_
|
schwehr/gdal-autotest2 | cpp/util/cpl_memory_closer.h | <filename>cpp/util/cpl_memory_closer.h
// Wrap CPLStrdup to call CPLFree when an instance goes out of scope.
//
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_CPL_MEMORY_CLOSER_H_
#define THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_CPL_MEMORY_CLOSER_H_
#include "port/cpl_conv.h"
namespace autotest2 {
// Use CPLFree to release the memory for a GDAL heap object.
// Similar to unique_ptr.
template <typename T>
class CPLMemoryCloser {
public:
explicit CPLMemoryCloser(T *data) {
the_data_ = data;
}
~CPLMemoryCloser() {
if (the_data_)
CPLFree(the_data_);
}
// Modifying the contents pointed to by the return is allowed.
T* const get() const {
return the_data_;
}
private:
T* the_data_;
};
} // namespace autotest2
#endif // THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_CPL_MEMORY_CLOSER_H_
|
schwehr/gdal-autotest2 | cpp/util/error_handler.h | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_ERROR_HANDLER_H_
#define THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_ERROR_HANDLER_H_
#include "port/cpl_error.h"
// Use gUnit LOG messages to emit GDAL log messages.
void CPLGoogleLogErrorHandler(CPLErr error_class,
int error_num,
const char *error_msg);
// Put an instance of this on the stack for noisy test cases.
class WithQuietHandler {
public:
WithQuietHandler() { CPLPushErrorHandler(CPLQuietErrorHandler); }
~WithQuietHandler() { CPLPopErrorHandler(); }
};
#endif // THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_ERROR_HANDLER_H_
|
schwehr/gdal-autotest2 | cpp/util/ogr/ogrfeaturedefn.h | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_OGR_OGRFEATUREDEFN_H_
#define THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_OGR_OGRFEATUREDEFN_H_
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "logging.h"
#include "third_party/absl/memory/memory.h"
#include "ogr/ogr_api.h"
#include "ogr/ogr_core.h"
#include "ogr/ogr_feature.h"
#include "port/cpl_port.h"
namespace autotest2 {
// Constructs instances of OGRFeatureDefn.
//
// Does not follow GDAL's internal default of having an initial geometry column.
// You must add all geometry columns.
//
// Use wkbUnknown for features that can have any type of geometry.
//
// Example:
//
// OGRFeatureDefnBuilder builder("schema");
// builder.AddGeom("geo", wkbPoint);
// builder.AddField("bool", OFTInteger, OFSTBoolean);
// builder.AddField("real", OFTReal, OFSTNone);
// OGRFeatureDefnReleaser fd(builder.Build());
// auto fd_cleaner = gtl::MakeCleanup([fd] { fd->Release(); });
// // Use fd.
class OGRFeatureDefnBuilder {
public:
OGRFeatureDefnBuilder(const char* name)
: feature_defn_(new OGRFeatureDefn(name)) {
feature_defn_->Reference();
feature_defn_->SetGeomType(wkbNone);
}
~OGRFeatureDefnBuilder() {
if (feature_defn_ != nullptr) feature_defn_->Release();
}
void AddGeom(const char* name, OGRwkbGeometryType geom_type) {
CHECK(feature_defn_ != nullptr) << "No changes allowed after build";
CHECK(geom_type != wkbNone) << "wkbNone is not allowed";
OGRGeomFieldDefn field_defn(name, geom_type);
feature_defn_->AddGeomFieldDefn(&field_defn);
}
void AddField(const char* name, OGRFieldType type, OGRFieldSubType subtype) {
CHECK(feature_defn_ != nullptr) << "No changes allowed after build";
OGRFieldDefn field_defn(name, type);
field_defn.SetSubType(subtype);
feature_defn_->AddFieldDefn(&field_defn);
}
// It is the callers responsibility to either pass off or call Release on the
// returned instance.
OGRFeatureDefn* Build() {
if (feature_defn_ == nullptr) {
// Building more than one time per instance is not allowed.
return nullptr;
}
// Set feature_defn_ to nullptr to block reuse of the builder.
auto feature_defn = feature_defn_;
feature_defn_ = nullptr;
return feature_defn;
}
private:
OGRFeatureDefn* feature_defn_;
};
} // namespace autotest2
#endif // THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_OGR_OGRFEATUREDEFN_H_
|
schwehr/gdal-autotest2 | cpp/util/vsimem.h | #ifndef THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_VSIMEM_H_
#define THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_VSIMEM_H_
#include <string>
#include "logging.h"
#include "port/cpl_vsi.h"
namespace autotest2 {
// Writes a buffer to an in-memory filesystem and deletes the file when the
// instance goes out of scope.
class VsiMemTempWrapper {
public:
VsiMemTempWrapper(const string &filename, const string &data)
: filename_(filename) {
VSILFILE *file = VSIFOpenL(filename.c_str(), "wb");
CHECK_NE(nullptr, file);
CHECK_EQ(1, VSIFWriteL(data.c_str(), data.length(), 1, file));
CHECK_EQ(0, VSIFCloseL(file));
}
~VsiMemTempWrapper() { CHECK_EQ(0, VSIUnlink(filename_.c_str())); }
private:
string filename_;
};
// Writes a buffer to an in-memory filesystem and deletes the file when the
// instance goes out of scope.
class VsiMemMaybeTempWrapper {
public:
VsiMemMaybeTempWrapper(const string &filename, const string &data, bool do_it)
: filename_(filename), do_it_(do_it) {
if (!do_it_) return;
VSILFILE *file = VSIFOpenL(filename.c_str(), "wb");
CHECK_NE(nullptr, file);
CHECK_EQ(1, VSIFWriteL(data.c_str(), data.length(), 1, file));
CHECK_EQ(0, VSIFCloseL(file));
}
~VsiMemMaybeTempWrapper() {
if (!do_it_) return;
CHECK_EQ(0, VSIUnlink(filename_.c_str()));
}
private:
string filename_;
bool do_it_;
};
} // namespace autotest2
#endif // THIRD_PARTY_GDAL_AUTOTEST2_CPP_UTIL_VSIMEM_H_
|
timwr/sigar | src/os/openbsd/openbsd_sigar.c | /*
* Copyright (c) 2004-2009 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2009-2010 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sigar.h"
#include "sigar_private.h"
#include "sigar_util.h"
#include "sigar_os.h"
#include <sys/param.h>
#include <sys/mount.h>
#include <nfs/rpcv2.h>
#include <nfs/nfsproto.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/user.h>
#include <sys/vmmeter.h>
#include <fcntl.h>
#include <stdio.h>
#include <nfs/nfs.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/proc.h>
#include <sys/resource.h>
#include <sys/sched.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <dirent.h>
#include <errno.h>
#include <sys/socketvar.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/tcp.h>
#include <netinet/tcp_timer.h>
#include <netinet/tcp_var.h>
#include <netinet/tcp_fsm.h>
#define NMIB(mib) (sizeof(mib)/sizeof(mib[0]))
#define KI_FD kp_proc.p_fd
#define KI_PID p_pid
#define KI_PPID kp_eproc.e_ppid
#define KI_PRI kp_proc.p_priority
#define KI_NICE kp_proc.p_nice
#define KI_COMM kp_proc.p_comm
#define KI_STAT kp_proc.p_stat
#define KI_UID kp_eproc.e_pcred.p_ruid
#define KI_GID kp_eproc.e_pcred.p_rgid
#define KI_EUID kp_eproc.e_pcred.p_svuid
#define KI_EGID kp_eproc.e_pcred.p_svgid
#define KI_SIZE XXX
#define KI_RSS kp_eproc.e_vm.vm_rssize
#define KI_TSZ kp_eproc.e_vm.vm_tsize
#define KI_DSZ kp_eproc.e_vm.vm_dsize
#define KI_SSZ kp_eproc.e_vm.vm_ssize
#define KI_FLAG p_eflag
#define KI_START kp_proc.p_starttime
#define PROCFS_STATUS(status) \
((((status) != SIGAR_OK) && !sigar->proc_mounted) ? \
SIGAR_ENOTIMPL : status)
static int get_koffsets(sigar_t *sigar)
{
int i;
struct nlist klist[] = {
{ "_cp_time" },
{ "_cnt" },
{ "_tcpstat" },
{ "_tcbtable" },
{ NULL }
};
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
kvm_nlist(sigar->kmem, klist);
for (i=0; i<KOFFSET_MAX; i++) {
sigar->koffsets[i] = klist[i].n_value;
}
return SIGAR_OK;
}
static int kread(sigar_t *sigar, void *data, int size, long offset)
{
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
if (kvm_read(sigar->kmem, offset, data, size) != size) {
return errno;
}
return SIGAR_OK;
}
int sigar_sys_info_get_uuid(sigar_t *sigar, char uuid[SIGAR_SYS_INFO_LEN])
{
return SIGAR_ENOTIMPL;
}
int sigar_os_open(sigar_t **sigar)
{
int mib[2];
int ncpu;
size_t len;
struct timeval boottime;
struct stat sb;
len = sizeof(ncpu);
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
if (sysctl(mib, NMIB(mib), &ncpu, &len, NULL, 0) < 0) {
return errno;
}
len = sizeof(boottime);
mib[0] = CTL_KERN;
mib[1] = KERN_BOOTTIME;
if (sysctl(mib, NMIB(mib), &boottime, &len, NULL, 0) < 0) {
return errno;
}
*sigar = malloc(sizeof(**sigar));
(*sigar)->kmem = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, NULL);
if (stat("/proc/curproc", &sb) < 0) {
(*sigar)->proc_mounted = 0;
}
else {
(*sigar)->proc_mounted = 1;
}
get_koffsets(*sigar);
(*sigar)->ncpu = ncpu;
(*sigar)->lcpu = -1;
(*sigar)->argmax = 0;
(*sigar)->boot_time = boottime.tv_sec; /* XXX seems off a bit */
(*sigar)->pagesize = getpagesize();
(*sigar)->ticks = sysconf(_SC_CLK_TCK);
(*sigar)->last_pid = -1;
(*sigar)->pinfo = NULL;
return SIGAR_OK;
}
int sigar_os_close(sigar_t *sigar)
{
if (sigar->pinfo) {
free(sigar->pinfo);
}
if (sigar->kmem) {
kvm_close(sigar->kmem);
}
free(sigar);
return SIGAR_OK;
}
char *sigar_os_error_string(sigar_t *sigar, int err)
{
switch (err) {
case SIGAR_EPERM_KMEM:
return "Failed to open /dev/kmem for reading";
case SIGAR_EPROC_NOENT:
return "/proc filesystem is not mounted";
default:
return NULL;
}
}
static int sigar_vmstat(sigar_t *sigar, struct uvmexp *vmstat)
{
size_t size = sizeof(*vmstat);
int mib[] = { CTL_VM, VM_UVMEXP };
if (sysctl(mib, NMIB(mib), vmstat, &size, NULL, 0) < 0) {
return errno;
}
else {
return SIGAR_OK;
}
}
int sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem)
{
sigar_uint64_t kern = 0;
unsigned long mem_total;
struct uvmexp vmstat;
int mib[2];
size_t len;
int status;
mib[0] = CTL_HW;
mib[1] = HW_PAGESIZE;
len = sizeof(sigar->pagesize);
if (sysctl(mib, NMIB(mib), &sigar->pagesize, &len, NULL, 0) < 0) {
return errno;
}
mib[1] = HW_PHYSMEM;
len = sizeof(mem_total);
if (sysctl(mib, NMIB(mib), &mem_total, &len, NULL, 0) < 0) {
return errno;
}
mem->total = mem_total;
if ((status = sigar_vmstat(sigar, &vmstat)) != SIGAR_OK) {
return status;
}
mem->free = vmstat.free;
kern = vmstat.inactive;
kern += vmstat.vnodepages + vmstat.vtextpages;
kern *= sigar->pagesize;
mem->used = mem->total - mem->free;
mem->actual_free = mem->free + kern;
mem->actual_used = mem->used - kern;
sigar_mem_calc_ram(sigar, mem);
return SIGAR_OK;
}
#define SWI_MAXMIB 3
#define getswapinfo_sysctl(swap_ary, swap_max) SIGAR_ENOTIMPL
#define SIGAR_FS_BLOCKS_TO_BYTES(val, bsize) ((val * bsize) >> 1)
int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap)
{
int status;
struct uvmexp vmstat;
if ((status = sigar_vmstat(sigar, &vmstat)) != SIGAR_OK) {
return status;
}
swap->total = vmstat.swpages * sigar->pagesize;
swap->used = vmstat.swpginuse * sigar->pagesize;
swap->free = swap->total - swap->used;
swap->page_in = vmstat.pageins;
swap->page_out = vmstat.pdpageouts;
return SIGAR_OK;
}
#ifndef KERN_CPTIME
#define KERN_CPTIME KERN_CP_TIME
#endif
typedef time_t cp_time_t;
int sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu)
{
int status;
cp_time_t cp_time[CPUSTATES];
size_t size = sizeof(cp_time);
int mib[] = { CTL_KERN, KERN_CPTIME };
if (sysctl(mib, NMIB(mib), &cp_time, &size, NULL, 0) == -1) {
status = errno;
} else {
status = SIGAR_OK;
}
if (status != SIGAR_OK) {
return status;
}
cpu->user = SIGAR_TICK2MSEC(cp_time[CP_USER]);
cpu->nice = SIGAR_TICK2MSEC(cp_time[CP_NICE]);
cpu->sys = SIGAR_TICK2MSEC(cp_time[CP_SYS]);
cpu->idle = SIGAR_TICK2MSEC(cp_time[CP_IDLE]);
cpu->wait = 0; /*N/A*/
cpu->irq = SIGAR_TICK2MSEC(cp_time[CP_INTR]);
cpu->soft_irq = 0; /*N/A*/
cpu->stolen = 0; /*N/A*/
cpu->total = cpu->user + cpu->nice + cpu->sys + cpu->idle + cpu->irq;
return SIGAR_OK;
}
int sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist)
{
int status, i;
sigar_cpu_t *cpu;
sigar_cpu_list_create(cpulist);
#ifdef HAVE_KERN_CP_TIMES
if ((status = sigar_cp_times_get(sigar, cpulist)) == SIGAR_OK) {
return SIGAR_OK;
}
#endif
/* XXX no multi cpu in freebsd < 7.0, howbout others?
* for now just report all metrics on the 1st cpu
* 0's for the rest
*/
cpu = &cpulist->data[cpulist->number++];
status = sigar_cpu_get(sigar, cpu);
if (status != SIGAR_OK) {
return status;
}
for (i=1; i<sigar->ncpu; i++) {
SIGAR_CPU_LIST_GROW(cpulist);
cpu = &cpulist->data[cpulist->number++];
SIGAR_ZERO(cpu);
}
return SIGAR_OK;
}
int sigar_uptime_get(sigar_t *sigar,
sigar_uptime_t *uptime)
{
uptime->uptime = time(NULL) - sigar->boot_time;
return SIGAR_OK;
}
int sigar_loadavg_get(sigar_t *sigar,
sigar_loadavg_t *loadavg)
{
loadavg->processor_queue = SIGAR_FIELD_NOTIMPL;
getloadavg(loadavg->loadavg, 3);
return SIGAR_OK;
}
int sigar_system_stats_get (sigar_t *sigar,
sigar_system_stats_t *system_stats)
{
return SIGAR_ENOTIMPL;
}
int sigar_os_proc_list_get(sigar_t *sigar,
sigar_proc_list_t *proclist)
{
int i, num;
struct kinfo_proc *proc;
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
proc = kvm_getprocs(sigar->kmem, KERN_PROC_ALL, 0, sizeof(*proc), &num);
for (i=0; i<num; i++) {
if (proc[i].KI_FLAG & P_SYSTEM) {
continue;
}
if (proc[i].KI_PID == 0) {
continue;
}
SIGAR_PROC_LIST_GROW(proclist);
proclist->data[proclist->number++] = proc[i].KI_PID;
}
return SIGAR_OK;
}
static int sigar_get_pinfo(sigar_t *sigar, sigar_pid_t pid)
{
/*
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0 };
*/
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0, sizeof(*sigar->pinfo), 1 };
size_t len = sizeof(*sigar->pinfo);
time_t timenow = time(NULL);
mib[3] = pid;
if (sigar->pinfo == NULL) {
sigar->pinfo = malloc(len);
}
if (sigar->last_pid == pid) {
if ((timenow - sigar->last_getprocs) < SIGAR_LAST_PROC_EXPIRE) {
return SIGAR_OK;
}
}
sigar->last_pid = pid;
sigar->last_getprocs = timenow;
if (sysctl(mib, NMIB(mib), sigar->pinfo, &len, NULL, 0) < 0) {
return errno;
}
return SIGAR_OK;
}
#if defined(SHARED_TEXT_REGION_SIZE) && defined(SHARED_DATA_REGION_SIZE)
# define GLOBAL_SHARED_SIZE (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE) /* 10.4 SDK */
#endif
int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_mem_t *procmem)
{
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
if (status != SIGAR_OK) {
return status;
}
procmem->size =
(pinfo->p_vm_tsize + pinfo->p_vm_dsize + pinfo->p_vm_ssize) * sigar->pagesize;
procmem->resident = pinfo->p_vm_rssize * sigar->pagesize;
procmem->share = SIGAR_FIELD_NOTIMPL;
procmem->minor_faults = pinfo->p_uru_minflt;
procmem->major_faults = pinfo->p_uru_majflt;
procmem->page_faults = procmem->minor_faults + procmem->major_faults;
return SIGAR_OK;
}
int sigar_proc_cumulative_disk_io_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_cumulative_disk_io_t *proc_cumulative_disk_io)
{
return SIGAR_ENOTIMPL;
}
int sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_cred_t *proccred)
{
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
if (status != SIGAR_OK) {
return status;
}
proccred->uid = pinfo->p_ruid;
proccred->gid = pinfo->p_rgid;
proccred->euid = pinfo->p_uid;
proccred->egid = pinfo->p_gid;
return SIGAR_OK;
}
#define tv2msec(tv) \
(((sigar_uint64_t)tv.tv_sec * SIGAR_MSEC) + (((sigar_uint64_t)tv.tv_usec) / 1000))
int sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_time_t *proctime)
{
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
if (status != SIGAR_OK) {
return status;
}
/* XXX *_usec */
proctime->user = pinfo->p_uutime_sec * SIGAR_MSEC;
proctime->sys = pinfo->p_ustime_sec * SIGAR_MSEC;
proctime->total = proctime->user + proctime->sys;
proctime->start_time = pinfo->p_ustart_sec * SIGAR_MSEC;
return SIGAR_OK;
}
int sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_state_t *procstate)
{
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
int state = pinfo->p_stat;
if (status != SIGAR_OK) {
return status;
}
SIGAR_SSTRCPY(procstate->name, pinfo->p_comm);
procstate->ppid = pinfo->p_ppid;
procstate->priority = pinfo->p_priority;
procstate->nice = pinfo->p_nice;
procstate->tty = pinfo->p_tdev;
procstate->threads = SIGAR_FIELD_NOTIMPL;
procstate->processor = pinfo->p_cpuid;
switch (state) {
case SIDL:
procstate->state = 'D';
break;
case SRUN:
#ifdef SONPROC
case SONPROC:
#endif
procstate->state = 'R';
break;
case SSLEEP:
procstate->state = 'S';
break;
case SSTOP:
procstate->state = 'T';
break;
case SZOMB:
procstate->state = 'Z';
break;
default:
procstate->state = '?';
break;
}
return SIGAR_OK;
}
int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_args_t *procargs)
{
char buffer[ARG_MAX+1], **ptr=(char **)buffer;
size_t len = sizeof(buffer);
int mib[] = { CTL_KERN, KERN_PROC_ARGS, 0, KERN_PROC_ARGV };
mib[2] = pid;
if (sysctl(mib, NMIB(mib), buffer, &len, NULL, 0) < 0) {
return errno;
}
if (len == 0) {
procargs->number = 0;
return SIGAR_OK;
}
for (; *ptr; ptr++) {
int alen = strlen(*ptr)+1;
char *arg = malloc(alen);
SIGAR_PROC_ARGS_GROW(procargs);
memcpy(arg, *ptr, alen);
procargs->data[procargs->number++] = arg;
}
return SIGAR_OK;
}
int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_env_t *procenv)
{
char **env;
struct kinfo_proc *pinfo;
int num;
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
pinfo = kvm_getprocs(sigar->kmem, KERN_PROC_PID, pid, sizeof(*pinfo), &num);
if (!pinfo || (num < 1)) {
return errno;
}
if (!(env = kvm_getenvv(sigar->kmem, pinfo, 9086))) {
return errno;
}
while (*env) {
char *ptr = *env++;
char *val = strchr(ptr, '=');
int klen, vlen, status;
char key[128]; /* XXX is there a max key size? */
if (val == NULL) {
/* not key=val format */
procenv->env_getter(procenv->data, ptr, strlen(ptr), NULL, 0);
break;
}
klen = val - ptr;
SIGAR_SSTRCPY(key, ptr);
key[klen] = '\0';
++val;
vlen = strlen(val);
status = procenv->env_getter(procenv->data,
key, klen, val, vlen);
if (status != SIGAR_OK) {
/* not an error; just stop iterating */
break;
}
ptr += (klen + 1 + vlen + 1);
}
return SIGAR_OK;
}
int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_fd_t *procfd)
{
return SIGAR_ENOTIMPL;
}
int sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_exe_t *procexe)
{
memset(procexe, 0, sizeof(*procexe));
int len;
char name[1024];
(void)SIGAR_PROC_FILENAME(name, pid, "/file");
if ((len = readlink(name, procexe->name,
sizeof(procexe->name)-1)) >= 0) {
procexe->name[len] = '\0';
}
procexe->arch = sigar_elf_file_guess_arch(sigar, procexe->name);
return SIGAR_OK;
}
int sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_modules_t *procmods)
{
#if defined(SIGAR_HAS_DLINFO_MODULES)
if (pid == sigar_pid_get(sigar)) {
return sigar_dlinfo_modules(sigar, procmods);
}
#endif
return SIGAR_ENOTIMPL;
}
#define SIGAR_MICROSEC2NANO(s) \
((sigar_uint64_t)(s) * (sigar_uint64_t)1000)
#define TIME_NSEC(t) \
(SIGAR_SEC2NANO((t).tv_sec) + SIGAR_MICROSEC2NANO((t).tv_usec))
int sigar_thread_cpu_get(sigar_t *sigar,
sigar_uint64_t id,
sigar_thread_cpu_t *cpu)
{
/* XXX this is not per-thread, it is for the whole-process.
* just want to use for the shell time command at the moment.
*/
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
cpu->user = TIME_NSEC(usage.ru_utime);
cpu->sys = TIME_NSEC(usage.ru_stime);
cpu->total = TIME_NSEC(usage.ru_utime) + TIME_NSEC(usage.ru_stime);
return SIGAR_OK;
}
int sigar_os_fs_type_get(sigar_file_system_t *fsp)
{
char *type = fsp->sys_type_name;
/* see sys/disklabel.h */
switch (*type) {
case 'f':
if (strEQ(type, "ffs")) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
}
break;
case 'h':
if (strEQ(type, "hfs")) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
}
break;
case 'u':
if (strEQ(type, "ufs")) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
}
break;
}
return fsp->type;
}
static void get_fs_options(char *opts, int osize, long flags)
{
*opts = '\0';
if (flags & MNT_RDONLY) strncat(opts, "ro", osize);
else strncat(opts, "rw", osize);
if (flags & MNT_SYNCHRONOUS) strncat(opts, ",sync", osize);
if (flags & MNT_NOEXEC) strncat(opts, ",noexec", osize);
if (flags & MNT_NOSUID) strncat(opts, ",nosuid", osize);
#ifdef MNT_NODEV
if (flags & MNT_NODEV) strncat(opts, ",nodev", osize);
#endif
#ifdef MNT_UNION
if (flags & MNT_UNION) strncat(opts, ",union", osize);
#endif
if (flags & MNT_ASYNC) strncat(opts, ",async", osize);
#ifdef MNT_NOATIME
if (flags & MNT_NOATIME) strncat(opts, ",noatime", osize);
#endif
#ifdef MNT_NOCLUSTERR
if (flags & MNT_NOCLUSTERR) strncat(opts, ",noclusterr", osize);
#endif
#ifdef MNT_NOCLUSTERW
if (flags & MNT_NOCLUSTERW) strncat(opts, ",noclusterw", osize);
#endif
#ifdef MNT_NOSYMFOLLOW
if (flags & MNT_NOSYMFOLLOW) strncat(opts, ",nosymfollow", osize);
#endif
#ifdef MNT_SUIDDIR
if (flags & MNT_SUIDDIR) strncat(opts, ",suiddir", osize);
#endif
#ifdef MNT_SOFTDEP
if (flags & MNT_SOFTDEP) strncat(opts, ",soft-updates", osize);
#endif
if (flags & MNT_LOCAL) strncat(opts, ",local", osize);
if (flags & MNT_QUOTA) strncat(opts, ",quota", osize);
if (flags & MNT_ROOTFS) strncat(opts, ",rootfs", osize);
#ifdef MNT_USER
if (flags & MNT_USER) strncat(opts, ",user", osize);
#endif
#ifdef MNT_IGNORE
if (flags & MNT_IGNORE) strncat(opts, ",ignore", osize);
#endif
if (flags & MNT_EXPORTED) strncat(opts, ",nfs", osize);
}
#define sigar_statfs statfs
#define sigar_getfsstat getfsstat
#define sigar_f_flags f_flags
int sigar_file_system_list_get(sigar_t *sigar,
sigar_file_system_list_t *fslist)
{
struct sigar_statfs *fs;
int num, i;
int is_debug = SIGAR_LOG_IS_DEBUG(sigar);
long len;
if ((num = sigar_getfsstat(NULL, 0, MNT_NOWAIT)) < 0) {
return errno;
}
len = sizeof(*fs) * num;
fs = malloc(len);
if ((num = sigar_getfsstat(fs, len, MNT_NOWAIT)) < 0) {
free(fs);
return errno;
}
sigar_file_system_list_create(fslist);
for (i=0; i<num; i++) {
sigar_file_system_t *fsp;
#ifdef MNT_AUTOMOUNTED
if (fs[i].sigar_f_flags & MNT_AUTOMOUNTED) {
if (is_debug) {
sigar_log_printf(sigar, SIGAR_LOG_DEBUG,
"[file_system_list] skipping automounted %s: %s",
fs[i].f_fstypename, fs[i].f_mntonname);
}
continue;
}
#endif
#ifdef MNT_RDONLY
if (fs[i].sigar_f_flags & MNT_RDONLY) {
/* e.g. ftp mount or .dmg image */
if (is_debug) {
sigar_log_printf(sigar, SIGAR_LOG_DEBUG,
"[file_system_list] skipping readonly %s: %s",
fs[i].f_fstypename, fs[i].f_mntonname);
}
continue;
}
#endif
SIGAR_FILE_SYSTEM_LIST_GROW(fslist);
fsp = &fslist->data[fslist->number++];
SIGAR_SSTRCPY(fsp->dir_name, fs[i].f_mntonname);
SIGAR_SSTRCPY(fsp->dev_name, fs[i].f_mntfromname);
SIGAR_SSTRCPY(fsp->sys_type_name, fs[i].f_fstypename);
get_fs_options(fsp->options, sizeof(fsp->options)-1, fs[i].sigar_f_flags);
sigar_fs_type_init(fsp);
}
free(fs);
return SIGAR_OK;
}
int sigar_disk_usage_get(sigar_t *sigar, const char *name,
sigar_disk_usage_t *disk)
{
SIGAR_DISK_STATS_INIT(disk);
return SIGAR_ENOTIMPL;
}
int sigar_file_system_usage_get(sigar_t *sigar,
const char *dirname,
sigar_file_system_usage_t *fsusage)
{
int status = sigar_statvfs(sigar, dirname, fsusage);
if (status != SIGAR_OK) {
return status;
}
fsusage->use_percent = sigar_file_system_usage_calc_used(sigar, fsusage);
sigar_disk_usage_get(sigar, dirname, &fsusage->disk);
return SIGAR_OK;
}
/* XXX FreeBSD 5.x+ only? */
#define CTL_HW_FREQ "machdep.tsc_freq"
int sigar_cpu_info_list_get(sigar_t *sigar,
sigar_cpu_info_list_t *cpu_infos)
{
int i;
unsigned int mhz, mhz_min, mhz_max;
int cache_size=SIGAR_FIELD_NOTIMPL;
size_t size;
char model[128], vendor[128], *ptr;
size = sizeof(mhz);
(void)sigar_cpu_core_count(sigar);
/*XXX OpenBSD*/
mhz = SIGAR_FIELD_NOTIMPL;
mhz_max = SIGAR_FIELD_NOTIMPL;
mhz_min = SIGAR_FIELD_NOTIMPL;
if (mhz != SIGAR_FIELD_NOTIMPL) {
mhz /= 1000000;
}
if (mhz_max != SIGAR_FIELD_NOTIMPL) {
mhz_max /= 1000000;
}
if (mhz_min != SIGAR_FIELD_NOTIMPL) {
mhz_min /= 1000000;
}
size = sizeof(model);
if (1) {
int mib[] = { CTL_HW, HW_MODEL };
size = sizeof(model);
if (sysctl(mib, NMIB(mib), &model[0], &size, NULL, 0) < 0) {
strlcpy(model, "Unknown", sizeof(model));
}
}
/* XXX not sure */
if (mhz_max == SIGAR_FIELD_NOTIMPL) {
mhz_max = 0;
}
if (mhz_min == SIGAR_FIELD_NOTIMPL) {
mhz_min = 0;
}
if ((ptr = strchr(model, ' '))) {
if (strstr(model, "Intel")) {
SIGAR_SSTRCPY(vendor, "Intel");
}
else if (strstr(model, "AMD")) {
SIGAR_SSTRCPY(vendor, "AMD");
}
else {
SIGAR_SSTRCPY(vendor, "Unknown");
}
SIGAR_SSTRCPY(model, ptr+1);
}
sigar_cpu_info_list_create(cpu_infos);
for (i=0; i<sigar->ncpu; i++) {
sigar_cpu_info_t *info;
SIGAR_CPU_INFO_LIST_GROW(cpu_infos);
info = &cpu_infos->data[cpu_infos->number++];
SIGAR_SSTRCPY(info->vendor, vendor);
SIGAR_SSTRCPY(info->model, model);
sigar_cpu_model_adjust(sigar, info);
info->mhz = mhz;
info->mhz_max = mhz_max;
info->mhz_min = mhz_min;
info->cache_size = cache_size;
info->total_cores = sigar->ncpu;
info->cores_per_socket = sigar->lcpu;
info->total_sockets = sigar_cpu_socket_count(sigar);
}
return SIGAR_OK;
}
#define rt_s_addr(sa) ((struct sockaddr_in *)(sa))->sin_addr.s_addr
#ifndef SA_SIZE
#define SA_SIZE(sa) \
( (!(sa) || ((struct sockaddr *)(sa))->sa_len == 0) ? \
sizeof(long) : \
1 + ( (((struct sockaddr *)(sa))->sa_len - 1) | (sizeof(long) - 1) ) )
#endif
int sigar_net_route_list_get(sigar_t *sigar,
sigar_net_route_list_t *routelist)
{
size_t needed;
int bit;
char *buf, *next, *lim;
struct rt_msghdr *rtm;
int mib[6] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_DUMP, 0 };
if (sysctl(mib, NMIB(mib), NULL, &needed, NULL, 0) < 0) {
return errno;
}
buf = malloc(needed);
if (sysctl(mib, NMIB(mib), buf, &needed, NULL, 0) < 0) {
free(buf);
return errno;
}
sigar_net_route_list_create(routelist);
lim = buf + needed;
for (next = buf; next < lim; next += rtm->rtm_msglen) {
struct sockaddr *sa;
sigar_net_route_t *route;
rtm = (struct rt_msghdr *)next;
if (rtm->rtm_type != RTM_GET) {
continue;
}
sa = (struct sockaddr *)(rtm + 1);
if (sa->sa_family != AF_INET) {
continue;
}
SIGAR_NET_ROUTE_LIST_GROW(routelist);
route = &routelist->data[routelist->number++];
SIGAR_ZERO(route);
route->flags = rtm->rtm_flags;
if_indextoname(rtm->rtm_index, route->ifname);
for (bit=RTA_DST;
bit && ((char *)sa < lim);
bit <<= 1)
{
if ((rtm->rtm_addrs & bit) == 0) {
continue;
}
switch (bit) {
case RTA_DST:
sigar_net_address_set(route->destination,
rt_s_addr(sa));
break;
case RTA_GATEWAY:
if (sa->sa_family == AF_INET) {
sigar_net_address_set(route->gateway,
rt_s_addr(sa));
}
break;
case RTA_NETMASK:
sigar_net_address_set(route->mask,
rt_s_addr(sa));
break;
case RTA_IFA:
break;
}
sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
}
}
free(buf);
return SIGAR_OK;
}
typedef enum {
IFMSG_ITER_LIST,
IFMSG_ITER_GET
} ifmsg_iter_e;
typedef struct {
const char *name;
ifmsg_iter_e type;
union {
sigar_net_interface_list_t *iflist;
struct if_msghdr *ifm;
} data;
} ifmsg_iter_t;
static int sigar_ifmsg_init(sigar_t *sigar)
{
int mib[] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_IFLIST, 0 };
size_t len;
if (sysctl(mib, NMIB(mib), NULL, &len, NULL, 0) < 0) {
return errno;
}
if (sigar->ifconf_len < len) {
sigar->ifconf_buf = realloc(sigar->ifconf_buf, len);
sigar->ifconf_len = len;
}
if (sysctl(mib, NMIB(mib), sigar->ifconf_buf, &len, NULL, 0) < 0) {
return errno;
}
return SIGAR_OK;
}
/**
* @param name name of the interface
* @param name_len length of name (w/o \0)
*/
static int has_ifaddr(char *name, size_t name_len)
{
int sock, status;
struct ifreq ifr;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return errno;
}
strncpy(ifr.ifr_name, name, MIN(sizeof(ifr.ifr_name) - 1, name_len));
ifr.ifr_name[MIN(sizeof(ifr.ifr_name) - 1, name_len)] = '\0';
if (ioctl(sock, SIOCGIFADDR, &ifr) == 0) {
status = SIGAR_OK;
}
else {
status = errno;
}
close(sock);
return status;
}
static int sigar_ifmsg_iter(sigar_t *sigar, ifmsg_iter_t *iter)
{
char *end = sigar->ifconf_buf + sigar->ifconf_len;
char *ptr = sigar->ifconf_buf;
if (iter->type == IFMSG_ITER_LIST) {
sigar_net_interface_list_create(iter->data.iflist);
}
while (ptr < end) {
char *name;
struct sockaddr_dl *sdl;
struct if_msghdr *ifm = (struct if_msghdr *)ptr;
if (ifm->ifm_type != RTM_IFINFO) {
break;
}
ptr += ifm->ifm_msglen;
while (ptr < end) {
struct if_msghdr *next = (struct if_msghdr *)ptr;
if (next->ifm_type != RTM_NEWADDR) {
break;
}
ptr += next->ifm_msglen;
}
sdl = (struct sockaddr_dl *)(ifm + 1);
if (sdl->sdl_family != AF_LINK) {
continue;
}
switch (iter->type) {
case IFMSG_ITER_LIST:
if (sdl->sdl_type == IFT_OTHER) {
if (has_ifaddr(sdl->sdl_data, sdl->sdl_nlen) != SIGAR_OK) {
break;
}
}
else if (!((sdl->sdl_type == IFT_ETHER) ||
(sdl->sdl_type == IFT_LOOP)))
{
break; /* XXX deal w/ other weirdo interfaces */
}
SIGAR_NET_IFLIST_GROW(iter->data.iflist);
/* sdl_data doesn't include a trailing \0, it is only sdl_nlen long */
name = malloc(sdl->sdl_nlen+1);
memcpy(name, sdl->sdl_data, sdl->sdl_nlen);
name[sdl->sdl_nlen] = '\0'; /* add the missing \0 */
iter->data.iflist->data[iter->data.iflist->number++] = name;
break;
case IFMSG_ITER_GET:
if (strlen(iter->name) == sdl->sdl_nlen && 0 == memcmp(iter->name, sdl->sdl_data, sdl->sdl_nlen)) {
iter->data.ifm = ifm;
return SIGAR_OK;
}
}
}
switch (iter->type) {
case IFMSG_ITER_LIST:
return SIGAR_OK;
case IFMSG_ITER_GET:
default:
return ENXIO;
}
}
int sigar_net_interface_list_get(sigar_t *sigar,
sigar_net_interface_list_t *iflist)
{
int status;
ifmsg_iter_t iter;
if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) {
return status;
}
iter.type = IFMSG_ITER_LIST;
iter.data.iflist = iflist;
return sigar_ifmsg_iter(sigar, &iter);
}
#include <ifaddrs.h>
/* in6_prefixlen derived from freebsd/sbin/ifconfig/af_inet6.c */
static int sigar_in6_prefixlen(struct sockaddr *netmask)
{
struct in6_addr *addr = SIGAR_SIN6_ADDR(netmask);
u_char *name = (u_char *)addr;
int size = sizeof(*addr);
int byte, bit, plen = 0;
for (byte = 0; byte < size; byte++, plen += 8) {
if (name[byte] != 0xff) {
break;
}
}
if (byte == size) {
return plen;
}
for (bit = 7; bit != 0; bit--, plen++) {
if (!(name[byte] & (1 << bit))) {
break;
}
}
for (; bit != 0; bit--) {
if (name[byte] & (1 << bit)) {
return 0;
}
}
byte++;
for (; byte < size; byte++) {
if (name[byte]) {
return 0;
}
}
return plen;
}
int sigar_net_interface_ipv6_config_get(sigar_t *sigar, const char *name,
sigar_net_interface_config_t *ifconfig)
{
int status = SIGAR_ENOENT;
struct ifaddrs *addrs, *ifa;
if (getifaddrs(&addrs) != 0) {
return errno;
}
for (ifa=addrs; ifa; ifa=ifa->ifa_next) {
if (ifa->ifa_addr &&
(ifa->ifa_addr->sa_family == AF_INET6) &&
strEQ(ifa->ifa_name, name))
{
status = SIGAR_OK;
break;
}
}
if (status == SIGAR_OK) {
struct in6_addr *addr = SIGAR_SIN6_ADDR(ifa->ifa_addr);
sigar_net_address6_set(ifconfig->address6, addr);
sigar_net_interface_scope6_set(ifconfig, addr);
ifconfig->prefix6_length = sigar_in6_prefixlen(ifa->ifa_netmask);
}
freeifaddrs(addrs);
return status;
}
int sigar_net_interface_config_get(sigar_t *sigar, const char *name,
sigar_net_interface_config_t *ifconfig)
{
int sock;
int status;
ifmsg_iter_t iter;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
struct ifreq ifr;
if (!name) {
return sigar_net_interface_config_primary_get(sigar, ifconfig);
}
if (sigar->ifconf_len == 0) {
if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) {
return status;
}
}
SIGAR_ZERO(ifconfig);
iter.type = IFMSG_ITER_GET;
iter.name = name;
if ((status = sigar_ifmsg_iter(sigar, &iter)) != SIGAR_OK) {
return status;
}
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return errno;
}
ifm = iter.data.ifm;
SIGAR_SSTRCPY(ifconfig->name, name);
sdl = (struct sockaddr_dl *)(ifm + 1);
sigar_net_address_mac_set(ifconfig->hwaddr,
LLADDR(sdl),
sdl->sdl_alen);
ifconfig->flags = ifm->ifm_flags;
ifconfig->mtu = ifm->ifm_data.ifi_mtu;
ifconfig->metric = ifm->ifm_data.ifi_metric;
SIGAR_SSTRCPY(ifr.ifr_name, name);
#define ifr_s_addr(ifr) \
((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr
if (!ioctl(sock, SIOCGIFADDR, &ifr)) {
sigar_net_address_set(ifconfig->address,
ifr_s_addr(ifr));
}
if (!ioctl(sock, SIOCGIFNETMASK, &ifr)) {
sigar_net_address_set(ifconfig->netmask,
ifr_s_addr(ifr));
}
if (ifconfig->flags & IFF_LOOPBACK) {
sigar_net_address_set(ifconfig->destination,
ifconfig->address.addr.in);
sigar_net_address_set(ifconfig->broadcast, 0);
SIGAR_SSTRCPY(ifconfig->type,
SIGAR_NIC_LOOPBACK);
}
else {
if (!ioctl(sock, SIOCGIFDSTADDR, &ifr)) {
sigar_net_address_set(ifconfig->destination,
ifr_s_addr(ifr));
}
if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) {
sigar_net_address_set(ifconfig->broadcast,
ifr_s_addr(ifr));
}
SIGAR_SSTRCPY(ifconfig->type,
SIGAR_NIC_ETHERNET);
}
close(sock);
/* XXX can we get a better description like win32? */
SIGAR_SSTRCPY(ifconfig->description,
ifconfig->name);
sigar_net_interface_ipv6_config_init(ifconfig);
sigar_net_interface_ipv6_config_get(sigar, name, ifconfig);
return SIGAR_OK;
}
int sigar_net_interface_stat_get(sigar_t *sigar, const char *name,
sigar_net_interface_stat_t *ifstat)
{
int status;
ifmsg_iter_t iter;
struct if_msghdr *ifm;
if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) {
return status;
}
iter.type = IFMSG_ITER_GET;
iter.name = name;
if ((status = sigar_ifmsg_iter(sigar, &iter)) != SIGAR_OK) {
return status;
}
ifm = iter.data.ifm;
ifstat->rx_bytes = ifm->ifm_data.ifi_ibytes;
ifstat->rx_packets = ifm->ifm_data.ifi_ipackets;
ifstat->rx_errors = ifm->ifm_data.ifi_ierrors;
ifstat->rx_dropped = ifm->ifm_data.ifi_iqdrops;
ifstat->rx_overruns = SIGAR_FIELD_NOTIMPL;
ifstat->rx_frame = SIGAR_FIELD_NOTIMPL;
ifstat->tx_bytes = ifm->ifm_data.ifi_obytes;
ifstat->tx_packets = ifm->ifm_data.ifi_opackets;
ifstat->tx_errors = ifm->ifm_data.ifi_oerrors;
ifstat->tx_collisions = ifm->ifm_data.ifi_collisions;
ifstat->tx_dropped = SIGAR_FIELD_NOTIMPL;
ifstat->tx_overruns = SIGAR_FIELD_NOTIMPL;
ifstat->tx_carrier = SIGAR_FIELD_NOTIMPL;
ifstat->speed = ifm->ifm_data.ifi_baudrate;
return SIGAR_OK;
}
static int net_connection_state_get(int state)
{
switch (state) {
case TCPS_CLOSED:
return SIGAR_TCP_CLOSE;
case TCPS_LISTEN:
return SIGAR_TCP_LISTEN;
case TCPS_SYN_SENT:
return SIGAR_TCP_SYN_SENT;
case TCPS_SYN_RECEIVED:
return SIGAR_TCP_SYN_RECV;
case TCPS_ESTABLISHED:
return SIGAR_TCP_ESTABLISHED;
case TCPS_CLOSE_WAIT:
return SIGAR_TCP_CLOSE_WAIT;
case TCPS_FIN_WAIT_1:
return SIGAR_TCP_FIN_WAIT1;
case TCPS_CLOSING:
return SIGAR_TCP_CLOSING;
case TCPS_LAST_ACK:
return SIGAR_TCP_LAST_ACK;
case TCPS_FIN_WAIT_2:
return SIGAR_TCP_FIN_WAIT2;
case TCPS_TIME_WAIT:
return SIGAR_TCP_TIME_WAIT;
default:
return SIGAR_TCP_UNKNOWN;
}
}
static int net_connection_get(sigar_net_connection_walker_t *walker, int proto)
{
return SIGAR_ENOTIMPL;
int status;
int istcp = 0, type;
int flags = walker->flags;
struct inpcbtable table;
struct inpcb *head, *next, *prev;
sigar_t *sigar = walker->sigar;
u_long offset;
switch (proto) {
case IPPROTO_TCP:
offset = sigar->koffsets[KOFFSET_TCBTABLE];
istcp = 1;
type = SIGAR_NETCONN_TCP;
break;
case IPPROTO_UDP:
default:
return SIGAR_ENOTIMPL;
}
status = kread(sigar, &table, sizeof(table), offset);
if (status != SIGAR_OK) {
return status;
}
prev = head =
(struct inpcb *)&TAILQ_FIRST(&((struct inpcbtable *)offset)->inpt_queue);
next = (struct inpcb *)TAILQ_FIRST(&table.inpt_queue);
while (next != head) {
struct inpcb inpcb;
struct tcpcb tcpcb;
struct socket socket;
status = kread(sigar, &inpcb, sizeof(inpcb), (long)next);
prev = next;
next = (struct inpcb *)TAILQ_NEXT(&inpcb, inp_queue);
kread(sigar, &socket, sizeof(socket), (u_long)inpcb.inp_socket);
if ((((flags & SIGAR_NETCONN_SERVER) && socket.so_qlimit) ||
((flags & SIGAR_NETCONN_CLIENT) && !socket.so_qlimit)))
{
sigar_net_connection_t conn;
SIGAR_ZERO(&conn);
if (istcp) {
kread(sigar, &tcpcb, sizeof(tcpcb), (u_long)inpcb.inp_ppcb);
}
if (inpcb.inp_flags & INP_IPV6) {
sigar_net_address6_set(conn.local_address,
&inpcb.inp_laddr6.s6_addr);
sigar_net_address6_set(conn.remote_address,
&inpcb.inp_faddr6.s6_addr);
} else {
sigar_net_address_set(conn.local_address,
inpcb.inp_laddr.s_addr);
sigar_net_address_set(conn.remote_address,
inpcb.inp_faddr.s_addr);
}
conn.local_port = ntohs(inpcb.inp_lport);
conn.remote_port = ntohs(inpcb.inp_fport);
conn.receive_queue = socket.so_rcv.sb_cc;
conn.send_queue = socket.so_snd.sb_cc;
conn.uid = socket.so_pgid;
conn.type = type;
if (!istcp) {
conn.state = SIGAR_TCP_UNKNOWN;
if (walker->add_connection(walker, &conn) != SIGAR_OK) {
break;
}
continue;
}
conn.state = net_connection_state_get(tcpcb.t_state);
if (walker->add_connection(walker, &conn) != SIGAR_OK) {
break;
}
}
}
return SIGAR_OK;
}
int sigar_net_connection_walk(sigar_net_connection_walker_t *walker)
{
int flags = walker->flags;
int status;
if (flags & SIGAR_NETCONN_TCP) {
status = net_connection_get(walker, IPPROTO_TCP);
if (status != SIGAR_OK) {
return status;
}
}
if (flags & SIGAR_NETCONN_UDP) {
status = net_connection_get(walker, IPPROTO_UDP);
if (status != SIGAR_OK) {
return status;
}
}
return SIGAR_OK;
}
SIGAR_DECLARE(int)
sigar_net_listeners_get(sigar_net_connection_walker_t *walker)
{
int i, status;
status = sigar_net_connection_walk(walker);
if (status != SIGAR_OK) {
return status;
}
sigar_net_connection_list_t *list = walker->data;
sigar_pid_t pid;
for (i = 0; i < list->number; i++) {
status = sigar_proc_port_get(walker->sigar, walker->flags,
list->data[i].local_port, &pid);
if (status == SIGAR_OK) {
list->data[i].pid = pid;
}
}
return SIGAR_OK;
}
SIGAR_DECLARE(int)
sigar_tcp_get(sigar_t *sigar,
sigar_tcp_t *tcp)
{
struct tcpstat mib;
int status =
kread(sigar, &mib, sizeof(mib),
sigar->koffsets[KOFFSET_TCPSTAT]);
if (status != SIGAR_OK) {
return status;
}
tcp->active_opens = mib.tcps_connattempt;
tcp->passive_opens = mib.tcps_accepts;
tcp->attempt_fails = mib.tcps_conndrops;
tcp->estab_resets = mib.tcps_drops;
if (sigar_tcp_curr_estab(sigar, tcp) != SIGAR_OK) {
tcp->curr_estab = -1;
}
tcp->in_segs = mib.tcps_rcvtotal;
tcp->out_segs = mib.tcps_sndtotal - mib.tcps_sndrexmitpack;
tcp->retrans_segs = mib.tcps_sndrexmitpack;
tcp->in_errs =
mib.tcps_rcvbadsum +
mib.tcps_rcvbadoff +
mib.tcps_rcvmemdrop +
mib.tcps_rcvshort;
tcp->out_rsts = -1; /* XXX mib.tcps_sndctrl - mib.tcps_closed; ? */
return SIGAR_OK;
}
static int get_nfsstats(struct nfsstats *stats)
{
size_t len = sizeof(*stats);
int mib[] = { CTL_VFS, 2, NFS_NFSSTATS };
if (sysctl(mib, NMIB(mib), stats, &len, NULL, 0) < 0) {
return errno;
}
else {
return SIGAR_OK;
}
}
typedef uint64_t rpc_cnt_t;
static void map_nfs_stats(sigar_nfs_v3_t *nfs, rpc_cnt_t *rpc)
{
nfs->null = rpc[NFSPROC_NULL];
nfs->getattr = rpc[NFSPROC_GETATTR];
nfs->setattr = rpc[NFSPROC_SETATTR];
nfs->lookup = rpc[NFSPROC_LOOKUP];
nfs->access = rpc[NFSPROC_ACCESS];
nfs->readlink = rpc[NFSPROC_READLINK];
nfs->read = rpc[NFSPROC_READ];
nfs->write = rpc[NFSPROC_WRITE];
nfs->create = rpc[NFSPROC_CREATE];
nfs->mkdir = rpc[NFSPROC_MKDIR];
nfs->symlink = rpc[NFSPROC_SYMLINK];
nfs->mknod = rpc[NFSPROC_MKNOD];
nfs->remove = rpc[NFSPROC_REMOVE];
nfs->rmdir = rpc[NFSPROC_RMDIR];
nfs->rename = rpc[NFSPROC_RENAME];
nfs->link = rpc[NFSPROC_LINK];
nfs->readdir = rpc[NFSPROC_READDIR];
nfs->readdirplus = rpc[NFSPROC_READDIRPLUS];
nfs->fsstat = rpc[NFSPROC_FSSTAT];
nfs->fsinfo = rpc[NFSPROC_FSINFO];
nfs->pathconf = rpc[NFSPROC_PATHCONF];
nfs->commit = rpc[NFSPROC_COMMIT];
}
int sigar_nfs_client_v2_get(sigar_t *sigar,
sigar_nfs_client_v2_t *nfs)
{
return SIGAR_ENOTIMPL;
}
int sigar_nfs_server_v2_get(sigar_t *sigar,
sigar_nfs_server_v2_t *nfs)
{
return SIGAR_ENOTIMPL;
}
int sigar_nfs_client_v3_get(sigar_t *sigar,
sigar_nfs_client_v3_t *nfs)
{
int status;
struct nfsstats stats;
if ((status = get_nfsstats(&stats)) != SIGAR_OK) {
return status;
}
map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.rpccnt[0]);
return SIGAR_OK;
}
int sigar_nfs_server_v3_get(sigar_t *sigar,
sigar_nfs_server_v3_t *nfs)
{
int status;
struct nfsstats stats;
if ((status = get_nfsstats(&stats)) != SIGAR_OK) {
return status;
}
map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.srvrpccnt[0]);
return SIGAR_OK;
}
static char *get_hw_type(int type)
{
switch (type) {
case IFT_ETHER:
return "ether";
case IFT_ISO88025:
return "tr";
case IFT_FDDI:
return "fddi";
case IFT_ATM:
return "atm";
case IFT_L2VLAN:
return "vlan";
case IFT_IEEE1394:
return "firewire";
#ifdef IFT_BRIDGE
case IFT_BRIDGE:
return "bridge";
#endif
default:
return "unknown";
}
}
int sigar_arp_list_get(sigar_t *sigar,
sigar_arp_list_t *arplist)
{
size_t needed;
char *lim, *buf, *next;
struct rt_msghdr *rtm;
struct sockaddr_inarp *sin;
struct sockaddr_dl *sdl;
int mib[] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_LLINFO };
if (sysctl(mib, NMIB(mib), NULL, &needed, NULL, 0) < 0) {
return errno;
}
if (needed == 0) { /* empty cache */
return 0;
}
buf = malloc(needed);
if (sysctl(mib, NMIB(mib), buf, &needed, NULL, 0) < 0) {
free(buf);
return errno;
}
sigar_arp_list_create(arplist);
lim = buf + needed;
for (next = buf; next < lim; next += rtm->rtm_msglen) {
sigar_arp_t *arp;
SIGAR_ARP_LIST_GROW(arplist);
arp = &arplist->data[arplist->number++];
rtm = (struct rt_msghdr *)next;
sin = (struct sockaddr_inarp *)(rtm + 1);
sdl = (struct sockaddr_dl *)((char *)sin + SA_SIZE(sin));
sigar_net_address_set(arp->address, sin->sin_addr.s_addr);
sigar_net_address_mac_set(arp->hwaddr, LLADDR(sdl), sdl->sdl_alen);
if_indextoname(sdl->sdl_index, arp->ifname);
arp->flags = rtm->rtm_flags;
SIGAR_SSTRCPY(arp->type, get_hw_type(sdl->sdl_type));
}
free(buf);
return SIGAR_OK;
}
int sigar_proc_port_get(sigar_t *sigar, int protocol,
unsigned long port, sigar_pid_t *pid)
{
return SIGAR_ENOTIMPL;
}
int sigar_os_sys_info_get(sigar_t *sigar,
sigar_sys_info_t *sysinfo)
{
char *ptr;
SIGAR_SSTRCPY(sysinfo->name, "OpenBSD");
SIGAR_SSTRCPY(sysinfo->vendor_name, sysinfo->name);
SIGAR_SSTRCPY(sysinfo->vendor, sysinfo->name);
SIGAR_SSTRCPY(sysinfo->vendor_version,
sysinfo->version);
if ((ptr = strstr(sysinfo->vendor_version, "-"))) {
/* STABLE, RELEASE, CURRENT */
*ptr++ = '\0';
SIGAR_SSTRCPY(sysinfo->vendor_code_name, ptr);
}
snprintf(sysinfo->description,
sizeof(sysinfo->description),
"%s %s",
sysinfo->name, sysinfo->version);
return SIGAR_OK;
}
int sigar_os_is_in_container(sigar_t *sigar)
{
return 0;
}
|
timwr/sigar | src/os/aix/sigar_os.h | /*
* Copyright (c) 2004-2007, 2009 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2010 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SIGAR_OS_H
#define SIGAR_OS_H
#include <fcntl.h>
#include <errno.h>
#include <dlfcn.h>
#include <procinfo.h>
#include <sys/resource.h>
enum {
KOFFSET_LOADAVG,
KOFFSET_VAR,
KOFFSET_SYSINFO,
KOFFSET_IFNET,
KOFFSET_VMINFO,
KOFFSET_CPUINFO,
KOFFSET_TCB,
KOFFSET_ARPTABSIZE,
KOFFSET_ARPTABP,
KOFFSET_MAX
};
typedef struct {
time_t mtime;
int num;
char **devs;
} swaps_t;
typedef int (*proc_fd_func_t) (sigar_t *, sigar_pid_t, sigar_proc_fd_t *);
struct sigar_t {
SIGAR_T_BASE;
int kmem;
/* offsets for seeking on kmem */
long koffsets[KOFFSET_MAX];
proc_fd_func_t getprocfd;
int pagesize;
swaps_t swaps;
time_t last_getprocs;
sigar_pid_t last_pid;
struct procsinfo64 *pinfo;
struct cpuinfo *cpuinfo;
int cpuinfo_size;
int cpu_mhz;
char model[128];
int aix_version;
int thrusage;
sigar_cache_t *diskmap;
};
#define SIGAR_EPERM_KMEM (SIGAR_OS_START_ERROR+EACCES)
#endif /* SIGAR_OS_H */
|
timwr/sigar | examples/sysinfo.c | /*
* Copyright (c) 2008 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include "sigar.h"
int main(int argc, char **argv)
{
int status;
sigar_t *sigar;
sigar_sys_info_t sysinfo;
sigar_open(&sigar);
status = sigar_sys_info_get(sigar, &sysinfo);
if (status != SIGAR_OK) {
printf("sys_info error: %d (%s)\n",
status, sigar_strerror(sigar, status));
exit(1);
}
printf("name: %s\n", sysinfo.name);
printf("version: %s\n", sysinfo.version);
printf("arch: %s\n", sysinfo.arch);
printf("machine: %s\n", sysinfo.machine);
printf("description: %s\n", sysinfo.description);
printf("patch_level: %s\n", sysinfo.patch_level);
printf("vendor: %s\n", sysinfo.vendor);
printf("vendor_version: %s\n", sysinfo.vendor_version);
printf("vendor_name: %s\n", sysinfo.vendor_name);
printf("vendor_code_name: %s\n", sysinfo.vendor_code_name);
printf("vendor_uuid: %s\n", sysinfo.uuid);
sigar_close(sigar);
return 0;
}
|
timwr/sigar | src/os/openbsd/sigar_os.h | /*
* Copyright (c) 2004-2006, 2008 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SIGAR_OS_H
#define SIGAR_OS_H
#include <kvm.h>
#include <sys/sysctl.h>
enum {
KOFFSET_CPUINFO,
KOFFSET_VMMETER,
KOFFSET_TCPSTAT,
KOFFSET_TCBTABLE,
KOFFSET_MAX
};
typedef struct kinfo_proc bsd_pinfo_t;
struct sigar_t {
SIGAR_T_BASE;
int pagesize;
time_t last_getprocs;
sigar_pid_t last_pid;
bsd_pinfo_t *pinfo;
int lcpu;
size_t argmax;
kvm_t *kmem;
/* offsets for seeking on kmem */
unsigned long koffsets[KOFFSET_MAX];
int proc_mounted;
};
#define SIGAR_EPERM_KMEM (SIGAR_OS_START_ERROR+EACCES)
#define SIGAR_EPROC_NOENT (SIGAR_OS_START_ERROR+2)
#endif /* SIGAR_OS_H */
|
timwr/sigar | examples/cpuinfo.c | /*
* Copyright (c) 2008 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include "sigar.h"
int main(int argc, char **argv) {
int status, i;
sigar_t *sigar;
sigar_cpu_list_t cpulist;
sigar_loadavg_t loadavg;
sigar_open(&sigar);
status = sigar_cpu_list_get(sigar, &cpulist);
if (status != SIGAR_OK) {
printf("cpu_list error: %d (%s)\n",
status, sigar_strerror(sigar, status));
exit(1);
}
printf("Number of CPUs: %d\n", (unsigned)cpulist.number);
for (i=0; i<cpulist.number; i++) {
sigar_cpu_t cpu = cpulist.data[i];
printf("CPU %d: User = %lu Sys = %lu Nice = %lu Idle = %lu Total = %lu\n",
i, (unsigned long)cpu.user, (unsigned long)cpu.sys,
(unsigned long)cpu.nice, (unsigned long)cpu.idle,
(unsigned long)cpu.total);
/*...*/
}
sigar_cpu_list_destroy(sigar, &cpulist);
status = sigar_loadavg_get(sigar, &loadavg);
if (status != SIGAR_OK) {
printf("sigar_loadavg_get: %d (%s)\n",
status, sigar_strerror(sigar, status));
exit(1);
}
printf("Processor Queue Length: %u\n", loadavg.processor_queue);
sigar_close(sigar);
return 0;
}
|
timwr/sigar | examples/sigar_ps.c | /*
* Copyright (c) 2006 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include "sigar.h"
int main(int argc, char **argv) {
int status, i;
sigar_t *sigar;
sigar_proc_list_t proclist;
sigar_open(&sigar);
status = sigar_proc_list_get(sigar, &proclist);
if (status != SIGAR_OK) {
printf("proc_list error: %d (%s)\n",
status, sigar_strerror(sigar, status));
exit(1);
}
for (i = 0; i < proclist.number; i++) {
sigar_pid_t pid = proclist.data[i];
sigar_proc_state_t pstate;
sigar_proc_exe_t pexe;
status = sigar_proc_state_get(sigar, pid, &pstate);
if (status != SIGAR_OK) {
#ifdef DEBUG
printf("error: %d (%s) proc_state(%d)\n",
status, sigar_strerror(sigar, status), pid);
#endif
printf("%d %s %s\n", (int)pid, "unknown", "unknown");
continue;
}
status = sigar_proc_exe_get(sigar, pid, &pexe);
if (status != SIGAR_OK) {
#ifdef DEBUG
printf("error: %d (%s) proc_exe(%d)\n",
status, sigar_strerror(sigar, status), pid);
#endif
printf("%d %s %s\n", (int)pid, "unknown", pstate.name);
continue;
}
printf("%d %s %s\n", (int)pid, pexe.arch, pstate.name);
}
sigar_proc_list_destroy(sigar, &proclist);
sigar_close(sigar);
return 0;
}
|
timwr/sigar | include/sigar_log.h | <gh_stars>10-100
/*
* Copyright (c) 2004, 2006 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SIGAR_LOG_H
#define SIGAR_LOG_H
#include <stdarg.h>
#define SIGAR_LOG_FATAL 0
#define SIGAR_LOG_ERROR 1
#define SIGAR_LOG_WARN 2
#define SIGAR_LOG_INFO 3
#define SIGAR_LOG_DEBUG 4
#define SIGAR_LOG_TRACE 5
#define SIGAR_LOG_IS_FATAL(sigar) \
(sigar->log_level >= SIGAR_LOG_FATAL)
#define SIGAR_LOG_IS_ERROR(sigar) \
(sigar->log_level >= SIGAR_LOG_ERROR)
#define SIGAR_LOG_IS_WARN(sigar) \
(sigar->log_level >= SIGAR_LOG_WARN)
#define SIGAR_LOG_IS_INFO(sigar) \
(sigar->log_level >= SIGAR_LOG_INFO)
#define SIGAR_LOG_IS_DEBUG(sigar) \
(sigar->log_level >= SIGAR_LOG_DEBUG)
#define SIGAR_LOG_IS_TRACE(sigar) \
(sigar->log_level >= SIGAR_LOG_TRACE)
#define SIGAR_STRINGIFY(n) #n
#define SIGAR_LOG_FILELINE \
__FILE__ ":" SIGAR_STRINGIFY(__LINE__)
#if defined(__GNUC__)
# if (__GNUC__ > 2)
# define SIGAR_FUNC __func__
# else
# define SIGAR_FUNC __FUNCTION__
# endif
#else
# define SIGAR_FUNC SIGAR_LOG_FILELINE
#endif
typedef void (*sigar_log_impl_t)(sigar_t *, void *, int, char *);
SIGAR_DECLARE(void) sigar_log_printf(sigar_t *sigar, int level,
const char *format, ...);
SIGAR_DECLARE(void) sigar_log(sigar_t *sigar, int level, char *message);
SIGAR_DECLARE(void) sigar_log_impl_set(sigar_t *sigar, void *data,
sigar_log_impl_t impl);
SIGAR_DECLARE(void) sigar_log_impl_file(sigar_t *sigar, void *data,
int level, char *message);
SIGAR_DECLARE(const char *) sigar_log_level_string_get(sigar_t *sigar);
SIGAR_DECLARE(int) sigar_log_level_get(sigar_t *sigar);
SIGAR_DECLARE(void) sigar_log_level_set(sigar_t *sigar, int level);
#endif /* SIGAR_LOG_H */
|
timwr/sigar | src/sigar_rma.c | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include "sigar.h"
#include "sigar_private.h"
#include "sigar_util.h"
#include "sigar_log.h"
/*
* Can be used internally to dump out table index/values.
*/
#ifdef DEBUG
static void rma_debug(sigar_rma_stat_t *rma)
{
int i;
printf("Table element count = %d\n", rma->element_count);
printf(" current_pos = %d\n", rma->current_pos);
for (i = 0; i < rma->element_count; i++) {
if (rma->samples[i].stime == 0) {
continue;
}
printf("%-3d (%-5f) ", i, rma->samples[i].value);
if (!((i + 1) % 10)) {
printf("\n");
}
}
}
#endif
SIGAR_DECLARE(int) sigar_rma_open(sigar_rma_stat_t **rma, sigar_rma_stat_opts_t *rma_opts)
{
int size;
if(!rma_opts || rma_opts->max_average_time == 0)
size = SIGAR_RMA_RATE_15_MIN;
else
size = rma_opts->max_average_time;
*rma = calloc(1, sizeof(sigar_rma_stat_t));
/* Allocate enough space to hold the longest period. */
(*rma)->element_count = size;
(*rma)->samples = calloc((*rma)->element_count, sizeof(sigar_rma_sample_t));
(*rma)->current_pos = 0;
return 0;
}
SIGAR_DECLARE(int) sigar_rma_close(sigar_rma_stat_t *rma)
{
if(rma)
{
if(rma->samples)
free(rma->samples);
free(rma);
}
return 0;
}
/*
* Add a sample and return the current 1m, 5m, 15m average
*/
SIGAR_DECLARE(int)
sigar_rma_add_fetch_std_sample(sigar_rma_stat_t * rma, float value,
sigar_int64_t cur_time_sec, sigar_loadavg_t *loadavg)
{
sigar_rma_add_sample(rma, value, cur_time_sec);
loadavg->loadavg[0] = sigar_rma_get_average(rma,
SIGAR_RMA_RATE_1_MIN, cur_time_sec, &loadavg->loadavg_result[0]);
loadavg->loadavg[1] = sigar_rma_get_average(rma,
SIGAR_RMA_RATE_5_MIN, cur_time_sec, &loadavg->loadavg_result[1]);
loadavg->loadavg[2] = sigar_rma_get_average(rma,
SIGAR_RMA_RATE_15_MIN, cur_time_sec, &loadavg->loadavg_result[2]);
return 0;
}
/*
* Add a sample and return the current averages. Any number of averages may be
* requested and the sample sizes are passed in the loadavg field.
*/
SIGAR_DECLARE(int)
sigar_rma_add_fetch_custom_sample( sigar_rma_stat_t * rma, float value,
sigar_int64_t cur_time_sec, sigar_loadavg_t *loadavg, int num_avg)
{
int i;
int avg_secs;
int result = 0;
if((result = sigar_rma_add_sample(rma, value, cur_time_sec)) < 0)
return result;
for (i = 0; i < num_avg; i++) {
avg_secs = loadavg->loadavg[i];
loadavg->loadavg[i] = sigar_rma_get_average(rma, avg_secs,
cur_time_sec, &loadavg->loadavg_result[i]);
if(result)
break;
}
return result;
}
static int next_pos(sigar_rma_stat_t * rma, int pos)
{
pos++;
if (pos >= rma->element_count) {
pos = 0;
}
return pos;
}
static int prev_pos(sigar_rma_stat_t * rma, int pos)
{
pos--;
if (pos < 0) {
pos = rma->element_count - 1;
}
return pos;
}
SIGAR_DECLARE(int)
sigar_rma_add_sample(sigar_rma_stat_t * rma,
float value, sigar_int64_t cur_time_sec)
{
if (rma == NULL) {
return -1;
}
sigar_rma_sample_t *sample = &rma->samples[rma->current_pos];
sample->value = value;
if (cur_time_sec != 0) {
sample->stime = cur_time_sec;
} else {
sample->stime = sigar_time_now_millis() / 1000;
}
rma->current_pos = next_pos(rma, rma->current_pos);
return 0;
}
SIGAR_DECLARE(float)
sigar_rma_get_average(sigar_rma_stat_t * rma, int rate,
sigar_int64_t cur_time_sec, int *result)
{
float avg = 0;
int pos;
int count;
sigar_rma_sample_t *sample;
*result = 0;
if (rma == NULL) {
*result = -1;
return 0.0;
}
/* Start at our current position and work backwards. */
pos = prev_pos(rma, rma->current_pos);
count = 0;
while (pos != rma->current_pos) {
sample = &rma->samples[pos];
if (sample->stime == 0 ||
(cur_time_sec - sample->stime > rate)) {
break;
}
avg += sample->value;
count++;
pos = prev_pos(rma, pos);
}
if (count == 0) {
*result = -1;
return 0.0;
}
return (avg / count);
}
|
timwr/sigar | src/os/darwin/if_types.h | <filename>src/os/darwin/if_types.h
/*
* Copyright (c) 1989 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)if_types.h 7.3 (Berkeley) 6/28/90
*/
/* interface types for benefit of parsing media address headers */
#define IFT_OTHER 0x1 /* none of the following */
#define IFT_1822 0x2 /* old-style arpanet imp */
#define IFT_HDH1822 0x3 /* HDH arpanet imp */
#define IFT_X25DDN 0x4 /* x25 to imp */
#define IFT_X25 0x5 /* PDN X25 interface */
#define IFT_ETHER 0x6 /* Ethernet I or II */
#define IFT_ISO88023 0x7 /* CMSA CD */
#define IFT_ISO88024 0x8 /* Token Bus */
#define IFT_ISO88025 0x9 /* Token Ring */
#define IFT_ISO88026 0xa /* MAN */
#define IFT_STARLAN 0xb
#define IFT_P10 0xc /* Proteon 10MBit ring */
#define IFT_P80 0xd /* Proteon 10MBit ring */
#define IFT_HY 0xe /* Hyperchannel */
#define IFT_FDDI 0xf
#define IFT_LAPB 0x10
#define IFT_SDLC 0x11
#define IFT_T1 0x12
#define IFT_CEPT 0x13
#define IFT_ISDNBASIC 0x14
#define IFT_ISDNPRIMARY 0x15
#define IFT_PTPSERIAL 0x16
#define IFT_LOOP 0x18 /* loopback */
#define IFT_EON 0x19 /* ISO over IP */
#define IFT_XETHER 0x1a /* obsolete 3MB experimental ethernet */
#define IFT_NSIP 0x1b /* XNS over IP */
#define IFT_SLIP 0x1c /* IP over generic TTY */
|
timwr/sigar | src/os/freebsd/freebsd_sigar.c | /*
* Copyright (c) 2004-2009 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2009-2010 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sigar.h"
#include "sigar_private.h"
#include "sigar_util.h"
#include "sigar_os.h"
#include <sys/param.h>
#include <sys/mount.h>
#if !(defined(__FreeBSD__) && (__FreeBSD_version >= 800000))
#include <nfs/rpcv2.h>
#endif
#include <nfs/nfsproto.h>
#include <sys/dkstat.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/user.h>
#include <sys/vmmeter.h>
#include <fcntl.h>
#include <stdio.h>
#if defined(__FreeBSD__) && (__FreeBSD_version >= 500013)
#define SIGAR_FREEBSD5_NFSSTAT
#include <nfsclient/nfs.h>
#include <nfsserver/nfs.h>
#else
#include <nfs/nfs.h>
#endif
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <dirent.h>
#include <errno.h>
#include <sys/socketvar.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/tcp.h>
#include <netinet/tcp_timer.h>
#include <netinet/tcp_var.h>
#include <netinet/tcp_fsm.h>
#define NMIB(mib) (sizeof(mib)/sizeof(mib[0]))
#ifdef __FreeBSD__
# if (__FreeBSD_version >= 500013)
# define SIGAR_FREEBSD5
# else
# define SIGAR_FREEBSD4
# endif
#endif
#if defined(SIGAR_FREEBSD5)
#define KI_FD ki_fd
#define KI_PID ki_pid
#define KI_PPID ki_ppid
#define KI_PRI ki_pri.pri_user
#define KI_NICE ki_nice
#define KI_COMM ki_comm
#define KI_STAT ki_stat
#define KI_UID ki_ruid
#define KI_GID ki_rgid
#define KI_EUID ki_svuid
#define KI_EGID ki_svgid
#define KI_SIZE ki_size
#define KI_RSS ki_rssize
#define KI_TSZ ki_tsize
#define KI_DSZ ki_dsize
#define KI_SSZ ki_ssize
#define KI_FLAG ki_flag
#define KI_START ki_start
#elif defined(SIGAR_FREEBSD4)
#define KI_FD kp_proc.p_fd
#define KI_PID kp_proc.p_pid
#define KI_PPID kp_eproc.e_ppid
#define KI_PRI kp_proc.p_priority
#define KI_NICE kp_proc.p_nice
#define KI_COMM kp_proc.p_comm
#define KI_STAT kp_proc.p_stat
#define KI_UID kp_eproc.e_pcred.p_ruid
#define KI_GID kp_eproc.e_pcred.p_rgid
#define KI_EUID kp_eproc.e_pcred.p_svuid
#define KI_EGID kp_eproc.e_pcred.p_svgid
#define KI_SIZE XXX
#define KI_RSS kp_eproc.e_vm.vm_rssize
#define KI_TSZ kp_eproc.e_vm.vm_tsize
#define KI_DSZ kp_eproc.e_vm.vm_dsize
#define KI_SSZ kp_eproc.e_vm.vm_ssize
#define KI_FLAG kp_eproc.e_flag
#define KI_START kp_proc.p_starttime
#endif
#define PROCFS_STATUS(status) \
((((status) != SIGAR_OK) && !sigar->proc_mounted) ? \
SIGAR_ENOTIMPL : status)
static int get_koffsets(sigar_t *sigar)
{
int i;
struct nlist klist[] = {
{ "_cp_time" },
{ "_cnt" },
{ NULL }
};
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
kvm_nlist(sigar->kmem, klist);
for (i=0; i<KOFFSET_MAX; i++) {
sigar->koffsets[i] = klist[i].n_value;
}
return SIGAR_OK;
}
static int kread(sigar_t *sigar, void *data, int size, long offset)
{
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
if (kvm_read(sigar->kmem, offset, data, size) != size) {
return errno;
}
return SIGAR_OK;
}
int sigar_sys_info_get_uuid(sigar_t *sigar, char uuid[SIGAR_SYS_INFO_LEN])
{
return SIGAR_ENOTIMPL;
}
int sigar_os_open(sigar_t **sigar)
{
int mib[2];
int ncpu;
size_t len;
struct timeval boottime;
struct stat sb;
len = sizeof(ncpu);
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
if (sysctl(mib, NMIB(mib), &ncpu, &len, NULL, 0) < 0) {
return errno;
}
len = sizeof(boottime);
mib[0] = CTL_KERN;
mib[1] = KERN_BOOTTIME;
if (sysctl(mib, NMIB(mib), &boottime, &len, NULL, 0) < 0) {
return errno;
}
*sigar = malloc(sizeof(**sigar));
(*sigar)->kmem = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL);
if (stat("/proc/curproc", &sb) < 0) {
(*sigar)->proc_mounted = 0;
}
else {
(*sigar)->proc_mounted = 1;
}
get_koffsets(*sigar);
(*sigar)->ncpu = ncpu;
(*sigar)->lcpu = -1;
(*sigar)->argmax = 0;
(*sigar)->boot_time = boottime.tv_sec; /* XXX seems off a bit */
(*sigar)->pagesize = getpagesize();
(*sigar)->ticks = 100; /* sysconf(_SC_CLK_TCK) == 128 !? */
(*sigar)->last_pid = -1;
(*sigar)->pinfo = NULL;
return SIGAR_OK;
}
int sigar_os_close(sigar_t *sigar)
{
if (sigar->pinfo) {
free(sigar->pinfo);
}
if (sigar->kmem) {
kvm_close(sigar->kmem);
}
free(sigar);
return SIGAR_OK;
}
char *sigar_os_error_string(sigar_t *sigar, int err)
{
switch (err) {
case SIGAR_EPERM_KMEM:
return "Failed to open /dev/kmem for reading";
case SIGAR_EPROC_NOENT:
return "/proc filesystem is not mounted";
default:
return NULL;
}
}
/* ARG_MAX in FreeBSD 6.0 == 262144, which blows up the stack */
#define SIGAR_ARG_MAX 65536
static int sigar_vmstat(sigar_t *sigar, struct vmmeter *vmstat)
{
int status;
size_t size = sizeof(unsigned int);
status = kread(sigar, vmstat, sizeof(*vmstat),
sigar->koffsets[KOFFSET_VMMETER]);
if (status == SIGAR_OK) {
return SIGAR_OK;
}
SIGAR_ZERO(vmstat);
/* derived from src/usr.bin/vmstat/vmstat.c */
/* only collect the ones we actually use */
#define GET_VM_STATS(cat, name, used) \
if (used) sysctlbyname("vm.stats." #cat "." #name, &vmstat->name, &size, NULL, 0)
/* sys */
GET_VM_STATS(sys, v_swtch, 0);
GET_VM_STATS(sys, v_trap, 0);
GET_VM_STATS(sys, v_syscall, 0);
GET_VM_STATS(sys, v_intr, 0);
GET_VM_STATS(sys, v_soft, 0);
/* vm */
GET_VM_STATS(vm, v_vm_faults, 0);
GET_VM_STATS(vm, v_cow_faults, 0);
GET_VM_STATS(vm, v_cow_optim, 0);
GET_VM_STATS(vm, v_zfod, 0);
GET_VM_STATS(vm, v_ozfod, 0);
GET_VM_STATS(vm, v_swapin, 1);
GET_VM_STATS(vm, v_swapout, 1);
GET_VM_STATS(vm, v_swappgsin, 0);
GET_VM_STATS(vm, v_swappgsout, 0);
GET_VM_STATS(vm, v_vnodein, 1);
GET_VM_STATS(vm, v_vnodeout, 1);
GET_VM_STATS(vm, v_vnodepgsin, 0);
GET_VM_STATS(vm, v_vnodepgsout, 0);
GET_VM_STATS(vm, v_intrans, 0);
GET_VM_STATS(vm, v_reactivated, 0);
GET_VM_STATS(vm, v_pdwakeups, 0);
GET_VM_STATS(vm, v_pdpages, 0);
GET_VM_STATS(vm, v_dfree, 0);
GET_VM_STATS(vm, v_pfree, 0);
GET_VM_STATS(vm, v_tfree, 0);
GET_VM_STATS(vm, v_page_size, 0);
GET_VM_STATS(vm, v_page_count, 0);
GET_VM_STATS(vm, v_free_reserved, 0);
GET_VM_STATS(vm, v_free_target, 0);
GET_VM_STATS(vm, v_free_min, 0);
GET_VM_STATS(vm, v_free_count, 1);
GET_VM_STATS(vm, v_wire_count, 0);
GET_VM_STATS(vm, v_active_count, 0);
GET_VM_STATS(vm, v_inactive_target, 0);
GET_VM_STATS(vm, v_inactive_count, 1);
GET_VM_STATS(vm, v_cache_count, 1);
#if (__FreeBSD_version < 1100079 )
GET_VM_STATS(vm, v_cache_min, 0);
GET_VM_STATS(vm, v_cache_max, 0);
#endif
GET_VM_STATS(vm, v_pageout_free_min, 0);
GET_VM_STATS(vm, v_interrupt_free_min, 0);
GET_VM_STATS(vm, v_forks, 0);
GET_VM_STATS(vm, v_vforks, 0);
GET_VM_STATS(vm, v_rforks, 0);
GET_VM_STATS(vm, v_kthreads, 0);
GET_VM_STATS(vm, v_forkpages, 0);
GET_VM_STATS(vm, v_vforkpages, 0);
GET_VM_STATS(vm, v_rforkpages, 0);
GET_VM_STATS(vm, v_kthreadpages, 0);
#undef GET_VM_STATS
return SIGAR_OK;
}
int sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem)
{
sigar_uint64_t kern = 0;
unsigned long mem_total;
struct vmmeter vmstat;
int mib[2];
size_t len;
int status;
mib[0] = CTL_HW;
mib[1] = HW_PAGESIZE;
len = sizeof(sigar->pagesize);
if (sysctl(mib, NMIB(mib), &sigar->pagesize, &len, NULL, 0) < 0) {
return errno;
}
mib[1] = HW_PHYSMEM;
len = sizeof(mem_total);
if (sysctl(mib, NMIB(mib), &mem_total, &len, NULL, 0) < 0) {
return errno;
}
mem->total = mem_total;
if ((status = sigar_vmstat(sigar, &vmstat)) == SIGAR_OK) {
kern = vmstat.v_cache_count + vmstat.v_inactive_count;
kern *= sigar->pagesize;
mem->free = vmstat.v_free_count;
mem->free *= sigar->pagesize;
}
mem->used = mem->total - mem->free;
mem->actual_free = mem->free + kern;
mem->actual_used = mem->used - kern;
sigar_mem_calc_ram(sigar, mem);
return SIGAR_OK;
}
#define SWI_MAXMIB 3
#ifdef SIGAR_FREEBSD5
/* code in this function is based on FreeBSD 5.3 kvm_getswapinfo.c */
static int getswapinfo_sysctl(struct kvm_swap *swap_ary,
int swap_max)
{
int ti, ttl;
size_t mibi, len, size;
int soid[SWI_MAXMIB];
struct xswdev xsd;
struct kvm_swap tot;
int unswdev, dmmax;
/* XXX this can be optimized by using os_open */
size = sizeof(dmmax);
if (sysctlbyname("vm.dmmax", &dmmax, &size, NULL, 0) == -1) {
return errno;
}
mibi = SWI_MAXMIB - 1;
if (sysctlnametomib("vm.swap_info", soid, &mibi) == -1) {
return errno;
}
bzero(&tot, sizeof(tot));
for (unswdev = 0;; unswdev++) {
soid[mibi] = unswdev;
len = sizeof(xsd);
if (sysctl(soid, mibi + 1, &xsd, &len, NULL, 0) == -1) {
if (errno == ENOENT) {
break;
}
return errno;
}
#if 0
if (len != sizeof(xsd)) {
_kvm_err(kd, kd->program, "struct xswdev has unexpected "
"size; kernel and libkvm out of sync?");
return -1;
}
if (xsd.xsw_version != XSWDEV_VERSION) {
_kvm_err(kd, kd->program, "struct xswdev version "
"mismatch; kernel and libkvm out of sync?");
return -1;
}
#endif
ttl = xsd.xsw_nblks - dmmax;
if (unswdev < swap_max - 1) {
bzero(&swap_ary[unswdev], sizeof(swap_ary[unswdev]));
swap_ary[unswdev].ksw_total = ttl;
swap_ary[unswdev].ksw_used = xsd.xsw_used;
swap_ary[unswdev].ksw_flags = xsd.xsw_flags;
}
tot.ksw_total += ttl;
tot.ksw_used += xsd.xsw_used;
}
ti = unswdev;
if (ti >= swap_max) {
ti = swap_max - 1;
}
if (ti >= 0) {
swap_ary[ti] = tot;
}
return SIGAR_OK;
}
#else
#define getswapinfo_sysctl(swap_ary, swap_max) SIGAR_ENOTIMPL
#endif
#define SIGAR_FS_BLOCKS_TO_BYTES(val, bsize) ((val * bsize) >> 1)
int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap)
{
int status;
struct kvm_swap kswap[1];
struct vmmeter vmstat;
if (getswapinfo_sysctl(kswap, 1) != SIGAR_OK) {
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
if (kvm_getswapinfo(sigar->kmem, kswap, 1, 0) < 0) {
return errno;
}
}
if (kswap[0].ksw_total == 0) {
swap->total = 0;
swap->used = 0;
swap->free = 0;
return SIGAR_OK;
}
swap->total = kswap[0].ksw_total * sigar->pagesize;
swap->used = kswap[0].ksw_used * sigar->pagesize;
swap->free = swap->total - swap->used;
if ((status = sigar_vmstat(sigar, &vmstat)) == SIGAR_OK) {
swap->page_in = vmstat.v_swapin + vmstat.v_vnodein;
swap->page_out = vmstat.v_swapout + vmstat.v_vnodeout;
}
else {
swap->page_in = swap->page_out = -1;
}
return SIGAR_OK;
}
#ifndef KERN_CPTIME
#define KERN_CPTIME KERN_CP_TIME
#endif
typedef unsigned long cp_time_t;
int sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu)
{
int status;
cp_time_t cp_time[CPUSTATES];
size_t size = sizeof(cp_time);
/* try sysctl first, does not require /dev/kmem perms */
if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) == -1) {
status = kread(sigar, &cp_time, sizeof(cp_time),
sigar->koffsets[KOFFSET_CPUINFO]);
}
else {
status = SIGAR_OK;
}
if (status != SIGAR_OK) {
return status;
}
cpu->user = SIGAR_TICK2MSEC(cp_time[CP_USER]);
cpu->nice = SIGAR_TICK2MSEC(cp_time[CP_NICE]);
cpu->sys = SIGAR_TICK2MSEC(cp_time[CP_SYS]);
cpu->idle = SIGAR_TICK2MSEC(cp_time[CP_IDLE]);
cpu->wait = 0; /*N/A*/
cpu->irq = SIGAR_TICK2MSEC(cp_time[CP_INTR]);
cpu->soft_irq = 0; /*N/A*/
cpu->stolen = 0; /*N/A*/
cpu->total = cpu->user + cpu->nice + cpu->sys + cpu->idle + cpu->irq;
return SIGAR_OK;
}
#if defined(__FreeBSD__) && (__FreeBSD_version >= 700000)
#define HAVE_KERN_CP_TIMES /* kern.cp_times came later than 7.0, not sure exactly when */
static int sigar_cp_times_get(sigar_t *sigar, sigar_cpu_list_t *cpulist)
{
int maxcpu, status;
size_t len = sizeof(maxcpu), size;
long *times;
if (sysctlbyname("kern.smp.maxcpus", &maxcpu, &len, NULL, 0) == -1) {
return errno;
}
size = sizeof(long) * maxcpu * CPUSTATES;
times = malloc(size);
if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1) {
status = errno;
}
else {
int i, maxid = (size / CPUSTATES / sizeof(long));
long *cp_time = times;
status = SIGAR_OK;
for (i=0; i<maxid; i++) {
sigar_cpu_t *cpu;
SIGAR_CPU_LIST_GROW(cpulist);
cpu = &cpulist->data[cpulist->number++];
cpu->user = SIGAR_TICK2MSEC(cp_time[CP_USER]);
cpu->nice = SIGAR_TICK2MSEC(cp_time[CP_NICE]);
cpu->sys = SIGAR_TICK2MSEC(cp_time[CP_SYS]);
cpu->idle = SIGAR_TICK2MSEC(cp_time[CP_IDLE]);
cpu->wait = 0; /*N/A*/
cpu->irq = SIGAR_TICK2MSEC(cp_time[CP_INTR]);
cpu->soft_irq = 0; /*N/A*/
cpu->stolen = 0; /*N/A*/
cpu->total = cpu->user + cpu->nice + cpu->sys + cpu->idle + cpu->irq;
cp_time += CPUSTATES;
}
}
free(times);
return status;
}
#endif
int sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist)
{
int status, i;
sigar_cpu_t *cpu;
sigar_cpu_list_create(cpulist);
#ifdef HAVE_KERN_CP_TIMES
if ((status = sigar_cp_times_get(sigar, cpulist)) == SIGAR_OK) {
return SIGAR_OK;
}
#endif
/* XXX no multi cpu in freebsd < 7.0, howbout others?
* for now just report all metrics on the 1st cpu
* 0's for the rest
*/
cpu = &cpulist->data[cpulist->number++];
status = sigar_cpu_get(sigar, cpu);
if (status != SIGAR_OK) {
return status;
}
for (i=1; i<sigar->ncpu; i++) {
SIGAR_CPU_LIST_GROW(cpulist);
cpu = &cpulist->data[cpulist->number++];
SIGAR_ZERO(cpu);
}
return SIGAR_OK;
}
int sigar_uptime_get(sigar_t *sigar,
sigar_uptime_t *uptime)
{
uptime->uptime = time(NULL) - sigar->boot_time;
return SIGAR_OK;
}
int sigar_loadavg_get(sigar_t *sigar,
sigar_loadavg_t *loadavg)
{
loadavg->processor_queue = SIGAR_FIELD_NOTIMPL;
getloadavg(loadavg->loadavg, 3);
return SIGAR_OK;
}
int sigar_system_stats_get (sigar_t *sigar,
sigar_system_stats_t *system_stats)
{
return SIGAR_ENOTIMPL;
}
static int proc_fd_get_count(sigar_t *sigar, sigar_pid_t pid, int *num)
{
sigar_proc_fd_t procfd;
if (sigar_proc_fd_get(sigar, pid, &procfd) == SIGAR_OK) {
*num = procfd.total;
} else {
return SIGAR_ENOTIMPL;
}
return SIGAR_OK;
}
#ifndef KERN_PROC_PROC
/* freebsd 4.x */
#define KERN_PROC_PROC KERN_PROC_ALL
#endif
int sigar_os_proc_list_get(sigar_t *sigar,
sigar_proc_list_t *proclist)
{
#if defined(SIGAR_FREEBSD5)
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PROC, 0 };
int i, num;
size_t len;
struct kinfo_proc *proc;
if (sysctl(mib, NMIB(mib), NULL, &len, NULL, 0) < 0) {
return errno;
}
proc = malloc(len);
if (sysctl(mib, NMIB(mib), proc, &len, NULL, 0) < 0) {
free(proc);
return errno;
}
num = len/sizeof(*proc);
for (i=0; i<num; i++) {
if (proc[i].KI_FLAG & P_SYSTEM) {
continue;
}
if (proc[i].KI_PID == 0) {
continue;
}
SIGAR_PROC_LIST_GROW(proclist);
proclist->data[proclist->number++] = proc[i].KI_PID;
}
free(proc);
return SIGAR_OK;
#else
int i, num;
struct kinfo_proc *proc;
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
proc = kvm_getprocs(sigar->kmem, KERN_PROC_PROC, 0, &num);
for (i=0; i<num; i++) {
if (proc[i].KI_FLAG & P_SYSTEM) {
continue;
}
SIGAR_PROC_LIST_GROW(proclist);
proclist->data[proclist->number++] = proc[i].KI_PID;
}
#endif
return SIGAR_OK;
}
static int sigar_get_pinfo(sigar_t *sigar, sigar_pid_t pid)
{
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0 };
size_t len = sizeof(*sigar->pinfo);
time_t timenow = time(NULL);
mib[3] = pid;
if (sigar->pinfo == NULL) {
sigar->pinfo = malloc(len);
}
if (sigar->last_pid == pid) {
if ((timenow - sigar->last_getprocs) < SIGAR_LAST_PROC_EXPIRE) {
return SIGAR_OK;
}
}
sigar->last_pid = pid;
sigar->last_getprocs = timenow;
if (sysctl(mib, NMIB(mib), sigar->pinfo, &len, NULL, 0) < 0) {
return errno;
}
return SIGAR_OK;
}
#if defined(SHARED_TEXT_REGION_SIZE) && defined(SHARED_DATA_REGION_SIZE)
# define GLOBAL_SHARED_SIZE (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE) /* 10.4 SDK */
#endif
int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_mem_t *procmem)
{
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
if (status != SIGAR_OK) {
return status;
}
procmem->size =
(pinfo->KI_TSZ + pinfo->KI_DSZ + pinfo->KI_SSZ) * sigar->pagesize;
procmem->resident = pinfo->KI_RSS * sigar->pagesize;
procmem->share = SIGAR_FIELD_NOTIMPL;
procmem->page_faults = SIGAR_FIELD_NOTIMPL;
procmem->minor_faults = SIGAR_FIELD_NOTIMPL;
procmem->major_faults = SIGAR_FIELD_NOTIMPL;
return SIGAR_OK;
}
int sigar_proc_cumulative_disk_io_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_cumulative_disk_io_t *proc_cumulative_disk_io)
{
return SIGAR_ENOTIMPL;
}
int sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_cred_t *proccred)
{
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
if (status != SIGAR_OK) {
return status;
}
#if defined(__OpenBSD__) || defined(__NetBSD__)
proccred->uid = pinfo->p_ruid;
proccred->gid = pinfo->p_rgid;
proccred->euid = pinfo->p_uid;
proccred->egid = pinfo->p_gid;
#else
proccred->uid = pinfo->KI_UID;
proccred->gid = pinfo->KI_GID;
proccred->euid = pinfo->KI_EUID;
proccred->egid = pinfo->KI_EGID;
#endif
return SIGAR_OK;
}
#define tv2msec(tv) \
(((sigar_uint64_t)tv.tv_sec * SIGAR_MSEC) + (((sigar_uint64_t)tv.tv_usec) / 1000))
int sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_time_t *proctime)
{
#ifdef SIGAR_FREEBSD4
struct user user;
#endif
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
if (status != SIGAR_OK) {
return status;
}
#if defined(SIGAR_FREEBSD5)
proctime->user = tv2msec(pinfo->ki_rusage.ru_utime);
proctime->sys = tv2msec(pinfo->ki_rusage.ru_stime);
proctime->total = proctime->user + proctime->sys;
proctime->start_time = tv2msec(pinfo->KI_START);
#elif defined(SIGAR_FREEBSD4)
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
status = kread(sigar, &user, sizeof(user),
(u_long)pinfo->kp_proc.p_addr);
if (status != SIGAR_OK) {
return status;
}
proctime->user = tv2msec(user.u_stats.p_ru.ru_utime);
proctime->sys = tv2msec(user.u_stats.p_ru.ru_stime);
proctime->total = proctime->user + proctime->sys;
proctime->start_time = tv2msec(user.u_stats.p_start);
#endif
return SIGAR_OK;
}
int sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_state_t *procstate)
{
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
int state = pinfo->KI_STAT;
if (status != SIGAR_OK) {
return status;
}
procstate->open_files = SIGAR_FIELD_NOTIMPL;
SIGAR_SSTRCPY(procstate->name, pinfo->KI_COMM);
procstate->ppid = pinfo->KI_PPID;
procstate->priority = pinfo->KI_PRI;
procstate->nice = pinfo->KI_NICE;
procstate->tty = SIGAR_FIELD_NOTIMPL; /*XXX*/
procstate->threads = SIGAR_FIELD_NOTIMPL;
procstate->processor = SIGAR_FIELD_NOTIMPL;
int num = 0;
status = proc_fd_get_count(sigar, pid, &num);
if (status == SIGAR_OK) {
procstate->open_files = num;
}
switch (state) {
case SIDL:
procstate->state = 'D';
break;
case SRUN:
#ifdef SONPROC
case SONPROC:
#endif
procstate->state = 'R';
break;
case SSLEEP:
procstate->state = 'S';
break;
case SSTOP:
procstate->state = 'T';
break;
case SZOMB:
procstate->state = 'Z';
break;
default:
procstate->state = '?';
break;
}
return SIGAR_OK;
}
int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_args_t *procargs)
{
char buffer[SIGAR_ARG_MAX+1], *ptr=buffer;
size_t len = sizeof(buffer);
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_ARGS, 0 };
mib[3] = pid;
if (sysctl(mib, NMIB(mib), buffer, &len, NULL, 0) < 0) {
return errno;
}
if (len == 0) {
procargs->number = 0;
return SIGAR_OK;
}
buffer[len] = '\0';
while (len > 0) {
int alen = strlen(ptr)+1;
char *arg = malloc(alen);
SIGAR_PROC_ARGS_GROW(procargs);
memcpy(arg, ptr, alen);
procargs->data[procargs->number++] = arg;
len -= alen;
if (len > 0) {
ptr += alen;
}
}
return SIGAR_OK;
}
int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_env_t *procenv)
{
char **env;
struct kinfo_proc *pinfo;
int num;
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
pinfo = kvm_getprocs(sigar->kmem, KERN_PROC_PID, pid, &num);
if (!pinfo || (num < 1)) {
return errno;
}
if (!(env = kvm_getenvv(sigar->kmem, pinfo, 9086))) {
return errno;
}
while (*env) {
char *ptr = *env++;
char *val = strchr(ptr, '=');
int klen, vlen, status;
char key[128]; /* XXX is there a max key size? */
if (val == NULL) {
/* not key=val format */
procenv->env_getter(procenv->data, ptr, strlen(ptr), NULL, 0);
break;
}
klen = val - ptr;
SIGAR_SSTRCPY(key, ptr);
key[klen] = '\0';
++val;
vlen = strlen(val);
status = procenv->env_getter(procenv->data,
key, klen, val, vlen);
if (status != SIGAR_OK) {
/* not an error; just stop iterating */
break;
}
ptr += (klen + 1 + vlen + 1);
}
return SIGAR_OK;
}
int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_fd_t *procfd)
{
int status;
bsd_pinfo_t *pinfo;
struct filedesc filed;
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
if ((status = sigar_get_pinfo(sigar, pid)) != SIGAR_OK) {
return status;
}
pinfo = sigar->pinfo;
status = kread(sigar, &filed, sizeof(filed), (u_long)pinfo->KI_FD);
if (status != SIGAR_OK) {
return status;
}
/* seems the same as the above */
procfd->total = filed.fd_lastfile;
return SIGAR_OK;
}
int sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_exe_t *procexe)
{
memset(procexe, 0, sizeof(*procexe));
int len;
char name[1024];
(void)SIGAR_PROC_FILENAME(name, pid, "/file");
if ((len = readlink(name, procexe->name,
sizeof(procexe->name)-1)) >= 0) {
procexe->name[len] = '\0';
}
procexe->arch = sigar_elf_file_guess_arch(sigar, procexe->name);
return SIGAR_OK;
}
int sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_modules_t *procmods)
{
#if defined(SIGAR_HAS_DLINFO_MODULES)
if (pid == sigar_pid_get(sigar)) {
return sigar_dlinfo_modules(sigar, procmods);
}
#endif
return SIGAR_ENOTIMPL;
}
#define SIGAR_MICROSEC2NANO(s) \
((sigar_uint64_t)(s) * (sigar_uint64_t)1000)
#define TIME_NSEC(t) \
(SIGAR_SEC2NANO((t).tv_sec) + SIGAR_MICROSEC2NANO((t).tv_usec))
int sigar_thread_cpu_get(sigar_t *sigar,
sigar_uint64_t id,
sigar_thread_cpu_t *cpu)
{
/* XXX this is not per-thread, it is for the whole-process.
* just want to use for the shell time command at the moment.
*/
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
cpu->user = TIME_NSEC(usage.ru_utime);
cpu->sys = TIME_NSEC(usage.ru_stime);
cpu->total = TIME_NSEC(usage.ru_utime) + TIME_NSEC(usage.ru_stime);
return SIGAR_OK;
}
int sigar_os_fs_type_get(sigar_file_system_t *fsp)
{
char *type = fsp->sys_type_name;
/* see sys/disklabel.h */
switch (*type) {
case 'f':
if (strEQ(type, "ffs")) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
}
break;
case 'h':
if (strEQ(type, "hfs")) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
}
break;
case 'u':
if (strEQ(type, "ufs")) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
}
break;
}
return fsp->type;
}
static void get_fs_options(char *opts, int osize, long flags)
{
*opts = '\0';
if (flags & MNT_RDONLY) strncat(opts, "ro", osize);
else strncat(opts, "rw", osize);
if (flags & MNT_SYNCHRONOUS) strncat(opts, ",sync", osize);
if (flags & MNT_NOEXEC) strncat(opts, ",noexec", osize);
if (flags & MNT_NOSUID) strncat(opts, ",nosuid", osize);
#ifdef MNT_NODEV
if (flags & MNT_NODEV) strncat(opts, ",nodev", osize);
#endif
#ifdef MNT_UNION
if (flags & MNT_UNION) strncat(opts, ",union", osize);
#endif
if (flags & MNT_ASYNC) strncat(opts, ",async", osize);
#ifdef MNT_NOATIME
if (flags & MNT_NOATIME) strncat(opts, ",noatime", osize);
#endif
#ifdef MNT_NOCLUSTERR
if (flags & MNT_NOCLUSTERR) strncat(opts, ",noclusterr", osize);
#endif
#ifdef MNT_NOCLUSTERW
if (flags & MNT_NOCLUSTERW) strncat(opts, ",noclusterw", osize);
#endif
#ifdef MNT_NOSYMFOLLOW
if (flags & MNT_NOSYMFOLLOW) strncat(opts, ",nosymfollow", osize);
#endif
#ifdef MNT_SUIDDIR
if (flags & MNT_SUIDDIR) strncat(opts, ",suiddir", osize);
#endif
#ifdef MNT_SOFTDEP
if (flags & MNT_SOFTDEP) strncat(opts, ",soft-updates", osize);
#endif
if (flags & MNT_LOCAL) strncat(opts, ",local", osize);
if (flags & MNT_QUOTA) strncat(opts, ",quota", osize);
if (flags & MNT_ROOTFS) strncat(opts, ",rootfs", osize);
#ifdef MNT_USER
if (flags & MNT_USER) strncat(opts, ",user", osize);
#endif
#ifdef MNT_IGNORE
if (flags & MNT_IGNORE) strncat(opts, ",ignore", osize);
#endif
if (flags & MNT_EXPORTED) strncat(opts, ",nfs", osize);
}
#ifdef __NetBSD__
#define sigar_statfs statvfs
#define sigar_getfsstat getvfsstat
#define sigar_f_flags f_flag
#else
#define sigar_statfs statfs
#define sigar_getfsstat getfsstat
#define sigar_f_flags f_flags
#endif
int sigar_file_system_list_get(sigar_t *sigar,
sigar_file_system_list_t *fslist)
{
struct sigar_statfs *fs;
int num, i;
int is_debug = SIGAR_LOG_IS_DEBUG(sigar);
long len;
if ((num = sigar_getfsstat(NULL, 0, MNT_NOWAIT)) < 0) {
return errno;
}
len = sizeof(*fs) * num;
fs = malloc(len);
if ((num = sigar_getfsstat(fs, len, MNT_NOWAIT)) < 0) {
free(fs);
return errno;
}
sigar_file_system_list_create(fslist);
for (i=0; i<num; i++) {
sigar_file_system_t *fsp;
#ifdef MNT_AUTOMOUNTED
if (fs[i].sigar_f_flags & MNT_AUTOMOUNTED) {
if (is_debug) {
sigar_log_printf(sigar, SIGAR_LOG_DEBUG,
"[file_system_list] skipping automounted %s: %s",
fs[i].f_fstypename, fs[i].f_mntonname);
}
continue;
}
#endif
#ifdef MNT_RDONLY
if (fs[i].sigar_f_flags & MNT_RDONLY) {
/* e.g. ftp mount or .dmg image */
if (is_debug) {
sigar_log_printf(sigar, SIGAR_LOG_DEBUG,
"[file_system_list] skipping readonly %s: %s",
fs[i].f_fstypename, fs[i].f_mntonname);
}
continue;
}
#endif
SIGAR_FILE_SYSTEM_LIST_GROW(fslist);
fsp = &fslist->data[fslist->number++];
SIGAR_SSTRCPY(fsp->dir_name, fs[i].f_mntonname);
SIGAR_SSTRCPY(fsp->dev_name, fs[i].f_mntfromname);
SIGAR_SSTRCPY(fsp->sys_type_name, fs[i].f_fstypename);
get_fs_options(fsp->options, sizeof(fsp->options)-1, fs[i].sigar_f_flags);
sigar_fs_type_init(fsp);
}
free(fs);
return SIGAR_OK;
}
int sigar_disk_usage_get(sigar_t *sigar, const char *name,
sigar_disk_usage_t *disk)
{
/* XXX incomplete */
struct sigar_statfs buf;
if (sigar_statfs(name, &buf) < 0) {
return errno;
}
SIGAR_DISK_STATS_INIT(disk);
disk->reads = buf.f_syncreads + buf.f_asyncreads;
disk->writes = buf.f_syncwrites + buf.f_asyncwrites;
return SIGAR_OK;
}
int sigar_file_system_usage_get(sigar_t *sigar,
const char *dirname,
sigar_file_system_usage_t *fsusage)
{
int status = sigar_statvfs(sigar, dirname, fsusage);
if (status != SIGAR_OK) {
return status;
}
fsusage->use_percent = sigar_file_system_usage_calc_used(sigar, fsusage);
sigar_disk_usage_get(sigar, dirname, &fsusage->disk);
return SIGAR_OK;
}
/* XXX FreeBSD 5.x+ only? */
#define CTL_HW_FREQ "machdep.tsc_freq"
int sigar_cpu_info_list_get(sigar_t *sigar,
sigar_cpu_info_list_t *cpu_infos)
{
int i;
unsigned int mhz, mhz_min, mhz_max;
int cache_size=SIGAR_FIELD_NOTIMPL;
size_t size;
char model[128], vendor[128], *ptr;
size = sizeof(mhz);
(void)sigar_cpu_core_count(sigar);
if (sysctlbyname(CTL_HW_FREQ, &mhz, &size, NULL, 0) < 0) {
mhz = SIGAR_FIELD_NOTIMPL;
}
/* TODO */
mhz_max = SIGAR_FIELD_NOTIMPL;
mhz_min = SIGAR_FIELD_NOTIMPL;
if (mhz != SIGAR_FIELD_NOTIMPL) {
mhz /= 1000000;
}
if (mhz_max != SIGAR_FIELD_NOTIMPL) {
mhz_max /= 1000000;
}
if (mhz_min != SIGAR_FIELD_NOTIMPL) {
mhz_min /= 1000000;
}
size = sizeof(model);
if (sysctlbyname("hw.model", &model, &size, NULL, 0) < 0) {
int mib[] = { CTL_HW, HW_MODEL };
size = sizeof(model);
if (sysctl(mib, NMIB(mib), &model[0], &size, NULL, 0) < 0) {
strcpy(model, "Unknown");
}
}
if (mhz == SIGAR_FIELD_NOTIMPL) {
/* freebsd4 */
mhz = sigar_cpu_mhz_from_model(model);
}
/* XXX not sure */
if (mhz_max == SIGAR_FIELD_NOTIMPL) {
mhz_max = 0;
}
if (mhz_min == SIGAR_FIELD_NOTIMPL) {
mhz_min = 0;
}
if ((ptr = strchr(model, ' '))) {
if (strstr(model, "Intel")) {
SIGAR_SSTRCPY(vendor, "Intel");
}
else if (strstr(model, "AMD")) {
SIGAR_SSTRCPY(vendor, "AMD");
}
else {
SIGAR_SSTRCPY(vendor, "Unknown");
}
SIGAR_SSTRCPY(model, ptr+1);
}
sigar_cpu_info_list_create(cpu_infos);
for (i=0; i<sigar->ncpu; i++) {
sigar_cpu_info_t *info;
SIGAR_CPU_INFO_LIST_GROW(cpu_infos);
info = &cpu_infos->data[cpu_infos->number++];
SIGAR_SSTRCPY(info->vendor, vendor);
SIGAR_SSTRCPY(info->model, model);
sigar_cpu_model_adjust(sigar, info);
info->mhz = mhz;
info->mhz_max = mhz_max;
info->mhz_min = mhz_min;
info->cache_size = cache_size;
info->total_cores = sigar->ncpu;
info->cores_per_socket = sigar->lcpu;
info->total_sockets = sigar_cpu_socket_count(sigar);
}
return SIGAR_OK;
}
#define rt_s_addr(sa) ((struct sockaddr_in *)(sa))->sin_addr.s_addr
#ifndef SA_SIZE
#define SA_SIZE(sa) \
( (!(sa) || ((struct sockaddr *)(sa))->sa_len == 0) ? \
sizeof(long) : \
1 + ( (((struct sockaddr *)(sa))->sa_len - 1) | (sizeof(long) - 1) ) )
#endif
int sigar_net_route_list_get(sigar_t *sigar,
sigar_net_route_list_t *routelist)
{
size_t needed;
int bit;
char *buf, *next, *lim;
struct rt_msghdr *rtm;
int mib[6] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_DUMP, 0 };
if (sysctl(mib, NMIB(mib), NULL, &needed, NULL, 0) < 0) {
return errno;
}
#if __FreeBSD_version >= 800000
if (needed == 0) {
return SIGAR_ENOTIMPL; /*XXX hoping this is an 8.0beta bug*/
}
#endif
buf = malloc(needed);
if (sysctl(mib, NMIB(mib), buf, &needed, NULL, 0) < 0) {
free(buf);
return errno;
}
sigar_net_route_list_create(routelist);
lim = buf + needed;
for (next = buf; next < lim; next += rtm->rtm_msglen) {
struct sockaddr *sa;
sigar_net_route_t *route;
rtm = (struct rt_msghdr *)next;
if (rtm->rtm_type != RTM_GET) {
continue;
}
sa = (struct sockaddr *)(rtm + 1);
if (sa->sa_family != AF_INET) {
continue;
}
SIGAR_NET_ROUTE_LIST_GROW(routelist);
route = &routelist->data[routelist->number++];
SIGAR_ZERO(route);
route->flags = rtm->rtm_flags;
if_indextoname(rtm->rtm_index, route->ifname);
for (bit=RTA_DST;
bit && ((char *)sa < lim);
bit <<= 1)
{
if ((rtm->rtm_addrs & bit) == 0) {
continue;
}
switch (bit) {
case RTA_DST:
sigar_net_address_set(route->destination,
rt_s_addr(sa));
break;
case RTA_GATEWAY:
if (sa->sa_family == AF_INET) {
sigar_net_address_set(route->gateway,
rt_s_addr(sa));
}
break;
case RTA_NETMASK:
sigar_net_address_set(route->mask,
rt_s_addr(sa));
break;
case RTA_IFA:
break;
}
sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
}
}
free(buf);
return SIGAR_OK;
}
typedef enum {
IFMSG_ITER_LIST,
IFMSG_ITER_GET
} ifmsg_iter_e;
typedef struct {
const char *name;
ifmsg_iter_e type;
union {
sigar_net_interface_list_t *iflist;
struct if_msghdr *ifm;
} data;
} ifmsg_iter_t;
static int sigar_ifmsg_init(sigar_t *sigar)
{
int mib[] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_IFLIST, 0 };
size_t len;
if (sysctl(mib, NMIB(mib), NULL, &len, NULL, 0) < 0) {
return errno;
}
if (sigar->ifconf_len < len) {
sigar->ifconf_buf = realloc(sigar->ifconf_buf, len);
sigar->ifconf_len = len;
}
if (sysctl(mib, NMIB(mib), sigar->ifconf_buf, &len, NULL, 0) < 0) {
return errno;
}
return SIGAR_OK;
}
/**
* @param name name of the interface
* @param name_len length of name (w/o \0)
*/
static int has_ifaddr(char *name, size_t name_len)
{
int sock, status;
struct ifreq ifr;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return errno;
}
strncpy(ifr.ifr_name, name, MIN(sizeof(ifr.ifr_name) - 1, name_len));
ifr.ifr_name[MIN(sizeof(ifr.ifr_name) - 1, name_len)] = '\0';
if (ioctl(sock, SIOCGIFADDR, &ifr) == 0) {
status = SIGAR_OK;
}
else {
status = errno;
}
close(sock);
return status;
}
static int sigar_ifmsg_iter(sigar_t *sigar, ifmsg_iter_t *iter)
{
char *end = sigar->ifconf_buf + sigar->ifconf_len;
char *ptr = sigar->ifconf_buf;
if (iter->type == IFMSG_ITER_LIST) {
sigar_net_interface_list_create(iter->data.iflist);
}
while (ptr < end) {
char *name;
struct sockaddr_dl *sdl;
struct if_msghdr *ifm = (struct if_msghdr *)ptr;
if (ifm->ifm_type != RTM_IFINFO) {
break;
}
ptr += ifm->ifm_msglen;
while (ptr < end) {
struct if_msghdr *next = (struct if_msghdr *)ptr;
if (next->ifm_type != RTM_NEWADDR) {
break;
}
ptr += next->ifm_msglen;
}
sdl = (struct sockaddr_dl *)(ifm + 1);
if (sdl->sdl_family != AF_LINK) {
continue;
}
switch (iter->type) {
case IFMSG_ITER_LIST:
if (sdl->sdl_type == IFT_OTHER) {
if (has_ifaddr(sdl->sdl_data, sdl->sdl_nlen) != SIGAR_OK) {
break;
}
}
else if (!((sdl->sdl_type == IFT_ETHER) ||
(sdl->sdl_type == IFT_LOOP)))
{
break; /* XXX deal w/ other weirdo interfaces */
}
SIGAR_NET_IFLIST_GROW(iter->data.iflist);
/* sdl_data doesn't include a trailing \0, it is only sdl_nlen long */
name = malloc(sdl->sdl_nlen+1);
memcpy(name, sdl->sdl_data, sdl->sdl_nlen);
name[sdl->sdl_nlen] = '\0'; /* add the missing \0 */
iter->data.iflist->data[iter->data.iflist->number++] = name;
break;
case IFMSG_ITER_GET:
if (strlen(iter->name) == sdl->sdl_nlen && 0 == memcmp(iter->name, sdl->sdl_data, sdl->sdl_nlen)) {
iter->data.ifm = ifm;
return SIGAR_OK;
}
}
}
switch (iter->type) {
case IFMSG_ITER_LIST:
return SIGAR_OK;
case IFMSG_ITER_GET:
default:
return ENXIO;
}
}
int sigar_net_interface_list_get(sigar_t *sigar,
sigar_net_interface_list_t *iflist)
{
int status;
ifmsg_iter_t iter;
if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) {
return status;
}
iter.type = IFMSG_ITER_LIST;
iter.data.iflist = iflist;
return sigar_ifmsg_iter(sigar, &iter);
}
#include <ifaddrs.h>
/* in6_prefixlen derived from freebsd/sbin/ifconfig/af_inet6.c */
static int sigar_in6_prefixlen(struct sockaddr *netmask)
{
struct in6_addr *addr = SIGAR_SIN6_ADDR(netmask);
u_char *name = (u_char *)addr;
int size = sizeof(*addr);
int byte, bit, plen = 0;
for (byte = 0; byte < size; byte++, plen += 8) {
if (name[byte] != 0xff) {
break;
}
}
if (byte == size) {
return plen;
}
for (bit = 7; bit != 0; bit--, plen++) {
if (!(name[byte] & (1 << bit))) {
break;
}
}
for (; bit != 0; bit--) {
if (name[byte] & (1 << bit)) {
return 0;
}
}
byte++;
for (; byte < size; byte++) {
if (name[byte]) {
return 0;
}
}
return plen;
}
int sigar_net_interface_ipv6_config_get(sigar_t *sigar, const char *name,
sigar_net_interface_config_t *ifconfig)
{
int status = SIGAR_ENOENT;
struct ifaddrs *addrs, *ifa;
if (getifaddrs(&addrs) != 0) {
return errno;
}
for (ifa=addrs; ifa; ifa=ifa->ifa_next) {
if (ifa->ifa_addr &&
(ifa->ifa_addr->sa_family == AF_INET6) &&
strEQ(ifa->ifa_name, name))
{
status = SIGAR_OK;
break;
}
}
if (status == SIGAR_OK) {
struct in6_addr *addr = SIGAR_SIN6_ADDR(ifa->ifa_addr);
sigar_net_address6_set(ifconfig->address6, addr);
sigar_net_interface_scope6_set(ifconfig, addr);
ifconfig->prefix6_length = sigar_in6_prefixlen(ifa->ifa_netmask);
}
freeifaddrs(addrs);
return status;
}
int sigar_net_interface_config_get(sigar_t *sigar, const char *name,
sigar_net_interface_config_t *ifconfig)
{
int sock;
int status;
ifmsg_iter_t iter;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
struct ifreq ifr;
if (!name) {
return sigar_net_interface_config_primary_get(sigar, ifconfig);
}
if (sigar->ifconf_len == 0) {
if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) {
return status;
}
}
SIGAR_ZERO(ifconfig);
iter.type = IFMSG_ITER_GET;
iter.name = name;
if ((status = sigar_ifmsg_iter(sigar, &iter)) != SIGAR_OK) {
return status;
}
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return errno;
}
ifm = iter.data.ifm;
SIGAR_SSTRCPY(ifconfig->name, name);
sdl = (struct sockaddr_dl *)(ifm + 1);
sigar_net_address_mac_set(ifconfig->hwaddr,
LLADDR(sdl),
sdl->sdl_alen);
ifconfig->flags = ifm->ifm_flags;
ifconfig->mtu = ifm->ifm_data.ifi_mtu;
ifconfig->metric = ifm->ifm_data.ifi_metric;
SIGAR_SSTRCPY(ifr.ifr_name, name);
#define ifr_s_addr(ifr) \
((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr
if (!ioctl(sock, SIOCGIFADDR, &ifr)) {
sigar_net_address_set(ifconfig->address,
ifr_s_addr(ifr));
}
if (!ioctl(sock, SIOCGIFNETMASK, &ifr)) {
sigar_net_address_set(ifconfig->netmask,
ifr_s_addr(ifr));
}
if (ifconfig->flags & IFF_LOOPBACK) {
sigar_net_address_set(ifconfig->destination,
ifconfig->address.addr.in);
sigar_net_address_set(ifconfig->broadcast, 0);
SIGAR_SSTRCPY(ifconfig->type,
SIGAR_NIC_LOOPBACK);
}
else {
if (!ioctl(sock, SIOCGIFDSTADDR, &ifr)) {
sigar_net_address_set(ifconfig->destination,
ifr_s_addr(ifr));
}
if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) {
sigar_net_address_set(ifconfig->broadcast,
ifr_s_addr(ifr));
}
SIGAR_SSTRCPY(ifconfig->type,
SIGAR_NIC_ETHERNET);
}
close(sock);
/* XXX can we get a better description like win32? */
SIGAR_SSTRCPY(ifconfig->description,
ifconfig->name);
sigar_net_interface_ipv6_config_init(ifconfig);
sigar_net_interface_ipv6_config_get(sigar, name, ifconfig);
return SIGAR_OK;
}
int sigar_net_interface_stat_get(sigar_t *sigar, const char *name,
sigar_net_interface_stat_t *ifstat)
{
int status;
ifmsg_iter_t iter;
struct if_msghdr *ifm;
if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) {
return status;
}
iter.type = IFMSG_ITER_GET;
iter.name = name;
if ((status = sigar_ifmsg_iter(sigar, &iter)) != SIGAR_OK) {
return status;
}
ifm = iter.data.ifm;
ifstat->rx_bytes = ifm->ifm_data.ifi_ibytes;
ifstat->rx_packets = ifm->ifm_data.ifi_ipackets;
ifstat->rx_errors = ifm->ifm_data.ifi_ierrors;
ifstat->rx_dropped = ifm->ifm_data.ifi_iqdrops;
ifstat->rx_overruns = SIGAR_FIELD_NOTIMPL;
ifstat->rx_frame = SIGAR_FIELD_NOTIMPL;
ifstat->tx_bytes = ifm->ifm_data.ifi_obytes;
ifstat->tx_packets = ifm->ifm_data.ifi_opackets;
ifstat->tx_errors = ifm->ifm_data.ifi_oerrors;
ifstat->tx_collisions = ifm->ifm_data.ifi_collisions;
ifstat->tx_dropped = SIGAR_FIELD_NOTIMPL;
ifstat->tx_overruns = SIGAR_FIELD_NOTIMPL;
ifstat->tx_carrier = SIGAR_FIELD_NOTIMPL;
ifstat->speed = ifm->ifm_data.ifi_baudrate;
return SIGAR_OK;
}
static int net_connection_state_get(int state)
{
switch (state) {
case TCPS_CLOSED:
return SIGAR_TCP_CLOSE;
case TCPS_LISTEN:
return SIGAR_TCP_LISTEN;
case TCPS_SYN_SENT:
return SIGAR_TCP_SYN_SENT;
case TCPS_SYN_RECEIVED:
return SIGAR_TCP_SYN_RECV;
case TCPS_ESTABLISHED:
return SIGAR_TCP_ESTABLISHED;
case TCPS_CLOSE_WAIT:
return SIGAR_TCP_CLOSE_WAIT;
case TCPS_FIN_WAIT_1:
return SIGAR_TCP_FIN_WAIT1;
case TCPS_CLOSING:
return SIGAR_TCP_CLOSING;
case TCPS_LAST_ACK:
return SIGAR_TCP_LAST_ACK;
case TCPS_FIN_WAIT_2:
return SIGAR_TCP_FIN_WAIT2;
case TCPS_TIME_WAIT:
return SIGAR_TCP_TIME_WAIT;
default:
return SIGAR_TCP_UNKNOWN;
}
}
#if defined(__OpenBSD__) || defined(__NetBSD__)
static int net_connection_get(sigar_net_connection_walker_t *walker, int proto)
{
int status;
int istcp = 0, type;
int flags = walker->flags;
struct inpcbtable table;
struct inpcb *head, *next, *prev;
sigar_t *sigar = walker->sigar;
u_long offset;
switch (proto) {
case IPPROTO_TCP:
offset = sigar->koffsets[KOFFSET_TCBTABLE];
istcp = 1;
type = SIGAR_NETCONN_TCP;
break;
case IPPROTO_UDP:
default:
return SIGAR_ENOTIMPL;
}
status = kread(sigar, &table, sizeof(table), offset);
if (status != SIGAR_OK) {
return status;
}
prev = head =
(struct inpcb *)&CIRCLEQ_FIRST(&((struct inpcbtable *)offset)->inpt_queue);
next = (struct inpcb *)CIRCLEQ_FIRST(&table.inpt_queue);
while (next != head) {
struct inpcb inpcb;
struct tcpcb tcpcb;
struct socket socket;
status = kread(sigar, &inpcb, sizeof(inpcb), (long)next);
prev = next;
next = (struct inpcb *)CIRCLEQ_NEXT(&inpcb, inp_queue);
kread(sigar, &socket, sizeof(socket), (u_long)inpcb.inp_socket);
if ((((flags & SIGAR_NETCONN_SERVER) && socket.so_qlimit) ||
((flags & SIGAR_NETCONN_CLIENT) && !socket.so_qlimit)))
{
sigar_net_connection_t conn;
SIGAR_ZERO(&conn);
if (istcp) {
kread(sigar, &tcpcb, sizeof(tcpcb), (u_long)inpcb.inp_ppcb);
}
#ifdef __NetBSD__
if (inpcb.inp_af == AF_INET6) {
/*XXX*/
continue;
}
#else
if (inpcb.inp_flags & INP_IPV6) {
sigar_net_address6_set(conn.local_address,
&inpcb.inp_laddr6.s6_addr);
sigar_net_address6_set(conn.remote_address,
&inpcb.inp_faddr6.s6_addr);
}
#endif
else {
sigar_net_address_set(conn.local_address,
inpcb.inp_laddr.s_addr);
sigar_net_address_set(conn.remote_address,
inpcb.inp_faddr.s_addr);
}
conn.local_port = ntohs(inpcb.inp_lport);
conn.remote_port = ntohs(inpcb.inp_fport);
conn.receive_queue = socket.so_rcv.sb_cc;
conn.send_queue = socket.so_snd.sb_cc;
conn.uid = socket.so_pgid;
conn.type = type;
if (!istcp) {
conn.state = SIGAR_TCP_UNKNOWN;
if (walker->add_connection(walker, &conn) != SIGAR_OK) {
break;
}
continue;
}
conn.state = net_connection_state_get(tcpcb.t_state);
if (walker->add_connection(walker, &conn) != SIGAR_OK) {
break;
}
}
}
return SIGAR_OK;
}
#else
static int net_connection_get(sigar_net_connection_walker_t *walker, int proto)
{
int flags = walker->flags;
int type, istcp = 0;
char *buf;
const char *mibvar;
struct tcpcb *tp = NULL;
struct inpcb *inp;
struct xinpgen *xig, *oxig;
struct xsocket *so;
size_t len;
switch (proto) {
case IPPROTO_TCP:
mibvar = "net.inet.tcp.pcblist";
istcp = 1;
type = SIGAR_NETCONN_TCP;
break;
case IPPROTO_UDP:
mibvar = "net.inet.udp.pcblist";
type = SIGAR_NETCONN_UDP;
break;
default:
mibvar = "net.inet.raw.pcblist";
type = SIGAR_NETCONN_RAW;
break;
}
len = 0;
if (sysctlbyname(mibvar, 0, &len, 0, 0) < 0) {
return errno;
}
if ((buf = malloc(len)) == 0) {
return errno;
}
if (sysctlbyname(mibvar, buf, &len, 0, 0) < 0) {
free(buf);
return errno;
}
oxig = xig = (struct xinpgen *)buf;
for (xig = (struct xinpgen *)((char *)xig + xig->xig_len);
xig->xig_len > sizeof(struct xinpgen);
xig = (struct xinpgen *)((char *)xig + xig->xig_len))
{
if (istcp) {
struct xtcpcb *cb = (struct xtcpcb *)xig;
tp = &cb->xt_tp;
inp = &cb->xt_inp;
so = &cb->xt_socket;
}
else {
struct xinpcb *cb = (struct xinpcb *)xig;
inp = &cb->xi_inp;
so = &cb->xi_socket;
}
if (so->xso_protocol != proto) {
continue;
}
if (inp->inp_gencnt > oxig->xig_gen) {
continue;
}
if ((((flags & SIGAR_NETCONN_SERVER) && so->so_qlimit) ||
((flags & SIGAR_NETCONN_CLIENT) && !so->so_qlimit)))
{
sigar_net_connection_t conn;
SIGAR_ZERO(&conn);
if (inp->inp_vflag & INP_IPV6) {
sigar_net_address6_set(conn.local_address,
&inp->in6p_laddr.s6_addr);
sigar_net_address6_set(conn.remote_address,
&inp->in6p_faddr.s6_addr);
}
else {
sigar_net_address_set(conn.local_address,
inp->inp_laddr.s_addr);
sigar_net_address_set(conn.remote_address,
inp->inp_faddr.s_addr);
}
conn.local_port = ntohs(inp->inp_lport);
conn.remote_port = ntohs(inp->inp_fport);
conn.receive_queue = so->so_rcv.sb_cc;
conn.send_queue = so->so_snd.sb_cc;
conn.uid = so->so_pgid;
conn.type = type;
if (!istcp) {
conn.state = SIGAR_TCP_UNKNOWN;
if (walker->add_connection(walker, &conn) != SIGAR_OK) {
break;
}
continue;
}
conn.state = net_connection_state_get(tp->t_state);
if (walker->add_connection(walker, &conn) != SIGAR_OK) {
break;
}
}
}
free(buf);
return SIGAR_OK;
}
#endif
int sigar_net_connection_walk(sigar_net_connection_walker_t *walker)
{
int flags = walker->flags;
int status;
if (flags & SIGAR_NETCONN_TCP) {
status = net_connection_get(walker, IPPROTO_TCP);
if (status != SIGAR_OK) {
return status;
}
}
if (flags & SIGAR_NETCONN_UDP) {
status = net_connection_get(walker, IPPROTO_UDP);
if (status != SIGAR_OK) {
return status;
}
}
return SIGAR_OK;
}
SIGAR_DECLARE(int)
sigar_net_listeners_get(sigar_net_connection_walker_t *walker)
{
int i, status;
status = sigar_net_connection_walk(walker);
if (status != SIGAR_OK) {
return status;
}
sigar_net_connection_list_t *list = walker->data;
sigar_pid_t pid;
for (i = 0; i < list->number; i++) {
status = sigar_proc_port_get(walker->sigar, walker->flags,
list->data[i].local_port, &pid);
if (status == SIGAR_OK) {
list->data[i].pid = pid;
}
}
return SIGAR_OK;
}
SIGAR_DECLARE(int)
sigar_tcp_get(sigar_t *sigar,
sigar_tcp_t *tcp)
{
struct tcpstat mib;
#if !defined(TCPCTL_STATS) && (defined(__OpenBSD__) || defined(__NetBSD__))
int status =
kread(sigar, &mib, sizeof(mib),
sigar->koffsets[KOFFSET_TCPSTAT]);
if (status != SIGAR_OK) {
return status;
}
#else
int var[4] = { CTL_NET, PF_INET, IPPROTO_TCP, TCPCTL_STATS };
size_t len = sizeof(mib);
if (sysctl(var, NMIB(var), &mib, &len, NULL, 0) < 0) {
return errno;
}
#endif
tcp->active_opens = mib.tcps_connattempt;
tcp->passive_opens = mib.tcps_accepts;
tcp->attempt_fails = mib.tcps_conndrops;
tcp->estab_resets = mib.tcps_drops;
if (sigar_tcp_curr_estab(sigar, tcp) != SIGAR_OK) {
tcp->curr_estab = -1;
}
tcp->in_segs = mib.tcps_rcvtotal;
tcp->out_segs = mib.tcps_sndtotal - mib.tcps_sndrexmitpack;
tcp->retrans_segs = mib.tcps_sndrexmitpack;
tcp->in_errs =
mib.tcps_rcvbadsum +
mib.tcps_rcvbadoff +
mib.tcps_rcvmemdrop +
mib.tcps_rcvshort;
tcp->out_rsts = -1; /* XXX mib.tcps_sndctrl - mib.tcps_closed; ? */
return SIGAR_OK;
}
#ifndef SIGAR_FREEBSD5_NFSSTAT
static int get_nfsstats(struct nfsstats *stats)
{
size_t len = sizeof(*stats);
int mib[] = { CTL_VFS, 2, NFS_NFSSTATS };
if (sysctl(mib, NMIB(mib), stats, &len, NULL, 0) < 0) {
return errno;
}
else {
return SIGAR_OK;
}
}
#endif
typedef int rpc_cnt_t;
static void map_nfs_stats(sigar_nfs_v3_t *nfs, rpc_cnt_t *rpc)
{
nfs->null = rpc[NFSPROC_NULL];
nfs->getattr = rpc[NFSPROC_GETATTR];
nfs->setattr = rpc[NFSPROC_SETATTR];
nfs->lookup = rpc[NFSPROC_LOOKUP];
nfs->access = rpc[NFSPROC_ACCESS];
nfs->readlink = rpc[NFSPROC_READLINK];
nfs->read = rpc[NFSPROC_READ];
nfs->write = rpc[NFSPROC_WRITE];
nfs->create = rpc[NFSPROC_CREATE];
nfs->mkdir = rpc[NFSPROC_MKDIR];
nfs->symlink = rpc[NFSPROC_SYMLINK];
nfs->mknod = rpc[NFSPROC_MKNOD];
nfs->remove = rpc[NFSPROC_REMOVE];
nfs->rmdir = rpc[NFSPROC_RMDIR];
nfs->rename = rpc[NFSPROC_RENAME];
nfs->link = rpc[NFSPROC_LINK];
nfs->readdir = rpc[NFSPROC_READDIR];
nfs->readdirplus = rpc[NFSPROC_READDIRPLUS];
nfs->fsstat = rpc[NFSPROC_FSSTAT];
nfs->fsinfo = rpc[NFSPROC_FSINFO];
nfs->pathconf = rpc[NFSPROC_PATHCONF];
nfs->commit = rpc[NFSPROC_COMMIT];
}
int sigar_nfs_client_v2_get(sigar_t *sigar,
sigar_nfs_client_v2_t *nfs)
{
return SIGAR_ENOTIMPL;
}
int sigar_nfs_server_v2_get(sigar_t *sigar,
sigar_nfs_server_v2_t *nfs)
{
return SIGAR_ENOTIMPL;
}
int sigar_nfs_client_v3_get(sigar_t *sigar,
sigar_nfs_client_v3_t *nfs)
{
#ifdef SIGAR_FREEBSD5_NFSSTAT
struct nfsstats stats;
size_t size = sizeof(stats);
if (sysctlbyname("vfs.nfs.nfsstats", &stats, &size, NULL, 0) == -1) {
return errno;
}
map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.rpccnt[0]);
#else
int status;
struct nfsstats stats;
if ((status = get_nfsstats(&stats)) != SIGAR_OK) {
return status;
}
map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.rpccnt[0]);
#endif
return SIGAR_OK;
}
int sigar_nfs_server_v3_get(sigar_t *sigar,
sigar_nfs_server_v3_t *nfs)
{
#ifdef SIGAR_FREEBSD5_NFSSTAT
struct nfsrvstats stats;
size_t size = sizeof(stats);
if (sysctlbyname("vfs.nfsrv.nfsrvstats", &stats, &size, NULL, 0) == -1) {
return errno;
}
map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.srvrpccnt[0]);
#else
int status;
struct nfsstats stats;
if ((status = get_nfsstats(&stats)) != SIGAR_OK) {
return status;
}
map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.srvrpccnt[0]);
#endif
return SIGAR_OK;
}
static char *get_hw_type(int type)
{
switch (type) {
case IFT_ETHER:
return "ether";
case IFT_ISO88025:
return "tr";
case IFT_FDDI:
return "fddi";
case IFT_ATM:
return "atm";
case IFT_L2VLAN:
return "vlan";
case IFT_IEEE1394:
return "firewire";
#ifdef IFT_BRIDGE
case IFT_BRIDGE:
return "bridge";
#endif
default:
return "unknown";
}
}
int sigar_arp_list_get(sigar_t *sigar,
sigar_arp_list_t *arplist)
{
size_t needed;
char *lim, *buf, *next;
struct rt_msghdr *rtm;
struct sockaddr_inarp *sin;
struct sockaddr_dl *sdl;
int mib[] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_LLINFO };
if (sysctl(mib, NMIB(mib), NULL, &needed, NULL, 0) < 0) {
return errno;
}
if (needed == 0) { /* empty cache */
return 0;
}
buf = malloc(needed);
if (sysctl(mib, NMIB(mib), buf, &needed, NULL, 0) < 0) {
free(buf);
return errno;
}
sigar_arp_list_create(arplist);
lim = buf + needed;
for (next = buf; next < lim; next += rtm->rtm_msglen) {
sigar_arp_t *arp;
SIGAR_ARP_LIST_GROW(arplist);
arp = &arplist->data[arplist->number++];
rtm = (struct rt_msghdr *)next;
sin = (struct sockaddr_inarp *)(rtm + 1);
sdl = (struct sockaddr_dl *)((char *)sin + SA_SIZE(sin));
sigar_net_address_set(arp->address, sin->sin_addr.s_addr);
sigar_net_address_mac_set(arp->hwaddr, LLADDR(sdl), sdl->sdl_alen);
if_indextoname(sdl->sdl_index, arp->ifname);
arp->flags = rtm->rtm_flags;
SIGAR_SSTRCPY(arp->type, get_hw_type(sdl->sdl_type));
}
free(buf);
return SIGAR_OK;
}
#if (__FreeBSD_version < 800000)
#define _KERNEL
#include <sys/file.h>
#undef _KERNEL
/* derived from
* /usr/ports/security/pidentd/work/pidentd-3.0.16/src/k_freebsd2.c
*/
int sigar_proc_port_get(sigar_t *sigar, int protocol,
unsigned long port, sigar_pid_t *pid)
{
struct nlist nl[2];
struct inpcbhead tcb;
struct socket *sockp = NULL;
struct kinfo_proc *pinfo;
struct inpcb *head, pcbp;
int i, nentries, status;
if (protocol != SIGAR_NETCONN_TCP) {
return SIGAR_ENOTIMPL;
}
if (!sigar->kmem) {
return SIGAR_EPERM_KMEM;
}
nl[0].n_name = "_tcb"; /* XXX cache */
nl[1].n_name = "";
if (kvm_nlist(sigar->kmem, nl) < 0) {
return errno;
}
status = kread(sigar, &tcb, sizeof(tcb), nl[0].n_value);
if (status != SIGAR_OK) {
return status;
}
for (head = tcb.lh_first; head != NULL;
head = pcbp.inp_list.le_next)
{
status = kread(sigar, &pcbp, sizeof(pcbp), (long)head);
if (status != SIGAR_OK) {
return status;
}
if (!(pcbp.inp_vflag & INP_IPV4)) {
continue;
}
if (pcbp.inp_fport != 0) {
continue;
}
if (ntohs(pcbp.inp_lport) == port) {
sockp = pcbp.inp_socket;
break;
}
}
if (!sockp) {
return ENOENT;
}
pinfo = kvm_getprocs(sigar->kmem, KERN_PROC_PROC, 0, &nentries);
if (!pinfo) {
return errno;
}
for (i=0; i<nentries; i++) {
if (pinfo[i].KI_FLAG & P_SYSTEM) {
continue;
}
if (pinfo[i].KI_FD) {
struct filedesc pfd;
struct file **ofiles, ofile;
int j, osize;
status = kread(sigar, &pfd, sizeof(pfd), (long)pinfo[i].KI_FD);
if (status != SIGAR_OK) {
return status;
}
osize = pfd.fd_nfiles * sizeof(struct file *);
ofiles = malloc(osize); /* XXX reuse */
if (!ofiles) {
return errno;
}
status = kread(sigar, ofiles, osize, (long)pfd.fd_ofiles);
if (status != SIGAR_OK) {
free(ofiles);
return status;
}
for (j=0; j<pfd.fd_nfiles; j++) {
if (!ofiles[j]) {
continue;
}
status = kread(sigar, &ofile, sizeof(ofile), (long)ofiles[j]);
if (status != SIGAR_OK) {
free(ofiles);
return status;
}
if (ofile.f_count == 0) {
continue;
}
if (ofile.f_type == DTYPE_SOCKET &&
(struct socket *)ofile.f_data == sockp)
{
*pid = pinfo[i].KI_PID;
free(ofiles);
return SIGAR_OK;
}
}
free(ofiles);
}
}
return ENOENT;
}
#else
int sigar_proc_port_get(sigar_t *sigar, int protocol,
unsigned long port, sigar_pid_t *pid)
{
return SIGAR_ENOTIMPL;
}
#endif
int sigar_os_sys_info_get(sigar_t *sigar,
sigar_sys_info_t *sysinfo)
{
char *ptr;
SIGAR_SSTRCPY(sysinfo->name, "FreeBSD");
SIGAR_SSTRCPY(sysinfo->vendor_name, sysinfo->name);
SIGAR_SSTRCPY(sysinfo->vendor, sysinfo->name);
SIGAR_SSTRCPY(sysinfo->vendor_version,
sysinfo->version);
if ((ptr = strstr(sysinfo->vendor_version, "-"))) {
/* STABLE, RELEASE, CURRENT */
*ptr++ = '\0';
SIGAR_SSTRCPY(sysinfo->vendor_code_name, ptr);
}
snprintf(sysinfo->description,
sizeof(sysinfo->description),
"%s %s",
sysinfo->name, sysinfo->version);
return SIGAR_OK;
}
int sigar_os_is_in_container(sigar_t *sigar)
{
return 0;
}
|
timwr/sigar | src/sigar_elf.c | #include <stdio.h>
#include <stdint.h>
#include <machine/endian.h>
#include "sigar.h"
#include "sigar_private.h"
#include "sigar_util.h"
#include "sigar_os.h"
#define EI_CLASS 4
#define ELFCLASS32 1
#define ELFCLASS64 2
#define EI_DATA 5
#define ELFDATA2LSB 1
#define ELFDATA2MSB 2
#define EI_NIDENT 16
union elf_ehdr {
struct {
unsigned char e_ident[EI_NIDENT];
uint16_t e_type;
uint16_t e_machine;
uint32_t e_version;
uint32_t e_entry;
uint32_t e_phoff;
uint32_t e_shoff;
uint32_t e_flags;
uint16_t e_ehsize;
uint16_t e_phentsize;
uint16_t e_phnum;
uint16_t e_shentsize;
uint16_t e_shnum;
uint16_t e_shstrndx;
} elf32;
struct {
unsigned char e_ident[EI_NIDENT];
uint16_t e_type;
uint16_t e_machine;
uint32_t e_version;
uint64_t e_entry;
uint64_t e_phoff;
uint64_t e_shoff;
uint32_t e_flags;
uint16_t e_ehsize;
uint16_t e_phentsize;
uint16_t e_phnum;
uint16_t e_shentsize;
uint16_t e_shnum;
uint16_t e_shstrndx;
} elf64;
};
static const char * elf_em_to_str(int em)
{
switch (em) {
case 0: return "none";
case 1: return "m32";
case 2: return "sparc";
case 3: return "x86";
case 4: return "68k";
case 5: return "88k";
case 7: return "860";
case 8: return "mips";
case 9: return "s370";
case 10: return "mips_rs3_le";
case 15: return "parisc";
case 17: return "vpp500";
case 18: return "sparc32plus";
case 19: return "960";
case 20: return "ppc";
case 21: return "ppc64";
case 22: return "s390";
case 36: return "v800";
case 37: return "fr20";
case 38: return "rh32";
case 39: return "rce";
case 40: return "arm";
case 41: return "fake_alpha";
case 42: return "sh";
case 43: return "sparcv9";
case 44: return "tricore";
case 45: return "arc";
case 46: return "h8_300";
case 47: return "h8_300h";
case 48: return "h8s";
case 49: return "h8_500";
case 50: return "ia_64";
case 51: return "mips_x";
case 52: return "coldfire";
case 53: return "68hc12";
case 54: return "mma";
case 55: return "pcp";
case 56: return "ncpu";
case 57: return "ndr1";
case 58: return "starcore";
case 59: return "me16";
case 60: return "st100";
case 61: return "tinyj";
case 62: return "x86_64";
case 63: return "pdsp";
case 66: return "fx66";
case 67: return "st9plus";
case 68: return "st7";
case 69: return "68hc16";
case 70: return "68hc11";
case 71: return "68hc08";
case 72: return "68hc05";
case 73: return "svx";
case 74: return "st19";
case 75: return "vax";
case 76: return "cris";
case 77: return "javelin";
case 78: return "firepath";
case 79: return "zsp";
case 80: return "mmix";
case 81: return "huany";
case 82: return "prism";
case 83: return "avr";
case 84: return "fr30";
case 85: return "d10v";
case 86: return "d30v";
case 87: return "v850";
case 88: return "m32r";
case 89: return "mn10300";
case 90: return "mn10200";
case 91: return "pj";
case 92: return "openrisc";
case 93: return "arc_a5";
case 94: return "xtensa";
case 113: return "altera_nios2";
case 183: return "aarch64";
case 188: return "tilepro";
case 189: return "microblaze";
case 191: return "tilegx";
case 192: return "num";
case 0x9026: return "alpha";
default: return "unknown";
}
}
static int elf_file_get_em(const char *path)
{
int em = -1;
union elf_ehdr hdr;
FILE *f = fopen(path, "rb");
if (f) {
if (fread(&hdr, 1, sizeof(hdr), f) != sizeof(hdr)) {
goto out;
}
if (hdr.elf32.e_ident[EI_CLASS] == ELFCLASS32) {
if (hdr.elf32.e_ident[EI_DATA] == ELFDATA2LSB) {
em = le16toh(hdr.elf32.e_machine);
} else if (hdr.elf32.e_ident[EI_DATA] == ELFDATA2MSB) {
em = be16toh(hdr.elf32.e_machine);
}
} else if (hdr.elf32.e_ident[EI_CLASS] == ELFCLASS64) {
if (hdr.elf64.e_ident[EI_DATA] == ELFDATA2LSB) {
em = le16toh(hdr.elf64.e_machine);
} else if (hdr.elf64.e_ident[EI_DATA] == ELFDATA2MSB) {
em = be16toh(hdr.elf64.e_machine);
}
}
}
out:
if (f) {
fclose(f);
}
return em;
}
const char *sigar_elf_file_get_arch(const char *path)
{
int em = elf_file_get_em(path);
return (em != -1) ? elf_em_to_str(em) : NULL;
}
const char *sigar_elf_file_guess_arch(sigar_t *sigar, const char *path)
{
int em = -1;
if (path != NULL && strlen(path) > 0)
em = elf_file_get_em(path);
return (em != -1) ? elf_em_to_str(em) : sigar->arch;
}
|
timwr/sigar | src/os/darwin/darwin_sigar.c | /*
* Copyright (c) 2004-2009 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2009-2010 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sigar.h"
#include "sigar_private.h"
#include "sigar_util.h"
#include "sigar_os.h"
#include "TargetConditionals.h"
#include <sys/param.h>
#include <sys/mount.h>
#if !TARGET_OS_IPHONE
#include <nfs/rpcv2.h>
#include <nfs/nfsproto.h>
#include <nfs/nfs.h>
#endif
#include <dlfcn.h>
#include <mach/mach_init.h>
#include <mach/message.h>
#include <mach/kern_return.h>
#include <mach/mach_host.h>
#include <mach/mach_traps.h>
#include <mach/mach_port.h>
#include <mach/task.h>
#include <mach/thread_act.h>
#include <mach/thread_info.h>
#include <mach/vm_map.h>
#if !TARGET_OS_IPHONE
#if !defined(HAVE_SHARED_REGION_H) && defined(__MAC_10_5) /* see Availability.h */
# define HAVE_SHARED_REGION_H /* suckit autoconf */
#endif
#ifdef HAVE_SHARED_REGION_H
#include <mach/shared_region.h> /* does not exist in 10.4 SDK */
#else
#include <mach/shared_memory_server.h> /* deprecated in Leopard */
#endif
#endif
#include <mach-o/dyld.h>
#define __OPENTRANSPORTPROVIDERS__
#if !TARGET_OS_IPHONE
#include <CoreServices/CoreServices.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOBSD.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOTypes.h>
#include <IOKit/storage/IOBlockStorageDriver.h>
#endif
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <net/if.h>
#include <net/if_dl.h>
#if TARGET_OS_IPHONE
#include "if_types.h"
#include "tcp_fsm.h"
#define RTM_NEWADDR 0xc /* address being added to iface */
#define RTM_IFINFO 0xe /* iface going up/down etc. */
#else
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#endif
#include <dirent.h>
#include <errno.h>
#include <sys/socketvar.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/tcp.h>
#include <netinet/tcp_timer.h>
#include <netinet/tcp_var.h>
#if !TARGET_OS_IPHONE
#include <netinet/tcp_fsm.h>
#endif
#include <sys/utsname.h>
#define NMIB(mib) (sizeof(mib)/sizeof(mib[0]))
#define KI_FD kp_proc.p_fd
#define KI_PID kp_proc.p_pid
#define KI_PPID kp_eproc.e_ppid
#define KI_PRI kp_proc.p_priority
#define KI_NICE kp_proc.p_nice
#define KI_COMM kp_proc.p_comm
#define KI_STAT kp_proc.p_stat
#define KI_UID kp_eproc.e_pcred.p_ruid
#define KI_GID kp_eproc.e_pcred.p_rgid
#define KI_EUID kp_eproc.e_pcred.p_svuid
#define KI_EGID kp_eproc.e_pcred.p_svgid
#define KI_SIZE XXX
#define KI_RSS kp_eproc.e_vm.vm_rssize
#define KI_TSZ kp_eproc.e_vm.vm_tsize
#define KI_DSZ kp_eproc.e_vm.vm_dsize
#define KI_SSZ kp_eproc.e_vm.vm_ssize
#define KI_FLAG kp_eproc.e_flag
#define KI_START kp_proc.p_starttime
int sigar_sys_info_get_uuid(sigar_t *sigar, char uuid[SIGAR_SYS_INFO_LEN])
{
return SIGAR_ENOTIMPL;
}
int sigar_os_open(sigar_t **sigar)
{
int mib[2];
int ncpu;
size_t len;
struct timeval boottime;
len = sizeof(ncpu);
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
if (sysctl(mib, NMIB(mib), &ncpu, &len, NULL, 0) < 0) {
return errno;
}
len = sizeof(boottime);
mib[0] = CTL_KERN;
mib[1] = KERN_BOOTTIME;
if (sysctl(mib, NMIB(mib), &boottime, &len, NULL, 0) < 0) {
return errno;
}
*sigar = malloc(sizeof(**sigar));
(*sigar)->mach_port = mach_host_self();
# ifdef DARWIN_HAS_LIBPROC_H
if (((*sigar)->libproc = dlopen("/usr/lib/libproc.dylib", 0))) {
(*sigar)->proc_pidinfo = dlsym((*sigar)->libproc, "proc_pidinfo");
(*sigar)->proc_pidfdinfo = dlsym((*sigar)->libproc, "proc_pidfdinfo");
}
# endif
(*sigar)->ncpu = ncpu;
(*sigar)->lcpu = -1;
(*sigar)->argmax = 0;
(*sigar)->boot_time = boottime.tv_sec; /* XXX seems off a bit */
(*sigar)->pagesize = getpagesize();
(*sigar)->ticks = sysconf(_SC_CLK_TCK);
(*sigar)->last_pid = -1;
(*sigar)->pinfo = NULL;
return SIGAR_OK;
}
int sigar_os_close(sigar_t *sigar)
{
if (sigar->pinfo) {
free(sigar->pinfo);
}
free(sigar);
return SIGAR_OK;
}
char *sigar_os_error_string(sigar_t *sigar, int err)
{
switch (err) {
case SIGAR_EPERM_KMEM:
return "Failed to open /dev/kmem for reading";
case SIGAR_EPROC_NOENT:
return "/proc filesystem is not mounted";
default:
return NULL;
}
}
/* ARG_MAX in FreeBSD 6.0 == 262144, which blows up the stack */
#define SIGAR_ARG_MAX 65536
static size_t sigar_argmax_get(sigar_t *sigar)
{
#ifdef KERN_ARGMAX
int mib[] = { CTL_KERN, KERN_ARGMAX };
size_t size = sizeof(sigar->argmax);
if (sigar->argmax != 0) {
return sigar->argmax;
}
if (sysctl(mib, NMIB(mib), &sigar->argmax, &size, NULL, 0) == 0) {
return sigar->argmax;
}
#endif
return SIGAR_ARG_MAX;
}
static int sigar_vmstat(sigar_t *sigar, vm_statistics_data_t *vmstat)
{
kern_return_t status;
mach_msg_type_number_t count = sizeof(*vmstat) / sizeof(integer_t);
status = host_statistics(sigar->mach_port, HOST_VM_INFO,
(host_info_t)vmstat, &count);
if (status == KERN_SUCCESS) {
return SIGAR_OK;
}
else {
return errno;
}
}
int sigar_mem_get(sigar_t *sigar, sigar_mem_t *mem)
{
sigar_uint64_t kern = 0;
vm_statistics_data_t vmstat;
uint64_t mem_total;
int mib[2];
size_t len;
int status;
mib[0] = CTL_HW;
mib[1] = HW_PAGESIZE;
len = sizeof(sigar->pagesize);
if (sysctl(mib, NMIB(mib), &sigar->pagesize, &len, NULL, 0) < 0) {
return errno;
}
mib[1] = HW_MEMSIZE;
len = sizeof(mem_total);
if (sysctl(mib, NMIB(mib), &mem_total, &len, NULL, 0) < 0) {
return errno;
}
mem->total = mem_total;
if ((status = sigar_vmstat(sigar, &vmstat)) != SIGAR_OK) {
return status;
}
mem->free = vmstat.free_count;
mem->free *= sigar->pagesize;
kern = vmstat.inactive_count;
kern *= sigar->pagesize;
mem->used = mem->total - mem->free;
mem->actual_free = mem->free + kern;
mem->actual_used = mem->used - kern;
sigar_mem_calc_ram(sigar, mem);
return SIGAR_OK;
}
#define SWI_MAXMIB 3
#define getswapinfo_sysctl(swap_ary, swap_max) SIGAR_ENOTIMPL
#define SIGAR_FS_BLOCKS_TO_BYTES(val, bsize) ((val * bsize) >> 1)
#define VM_DIR "/private/var/vm"
#define SWAPFILE "swapfile"
static int sigar_swap_fs_get(sigar_t *sigar, sigar_swap_t *swap) /* <= 10.3 */
{
DIR *dirp;
struct dirent *ent;
char swapfile[SSTRLEN(VM_DIR) + SSTRLEN("/") + SSTRLEN(SWAPFILE) + 12];
struct stat swapstat;
struct statfs vmfs;
sigar_uint64_t val, bsize;
swap->used = swap->total = swap->free = 0;
if (!(dirp = opendir(VM_DIR))) {
return errno;
}
/* looking for "swapfile0", "swapfile1", etc. */
while ((ent = readdir(dirp))) {
char *ptr = swapfile;
if ((ent->d_namlen < SSTRLEN(SWAPFILE)+1) || /* n/a, see comment above */
(ent->d_namlen > SSTRLEN(SWAPFILE)+11)) /* ensure no overflow */
{
continue;
}
if (!strnEQ(ent->d_name, SWAPFILE, SSTRLEN(SWAPFILE))) {
continue;
}
/* sprintf(swapfile, "%s/%s", VM_DIR, ent->d_name) */
memcpy(ptr, VM_DIR, SSTRLEN(VM_DIR));
ptr += SSTRLEN(VM_DIR);
*ptr++ = '/';
memcpy(ptr, ent->d_name, ent->d_namlen+1);
if (stat(swapfile, &swapstat) < 0) {
continue;
}
swap->used += swapstat.st_size;
}
closedir(dirp);
if (statfs(VM_DIR, &vmfs) < 0) {
return errno;
}
bsize = vmfs.f_bsize / 512;
val = vmfs.f_bfree;
swap->total = SIGAR_FS_BLOCKS_TO_BYTES(val, bsize) + swap->used;
swap->free = swap->total - swap->used;
return SIGAR_OK;
}
static int sigar_swap_sysctl_get(sigar_t *sigar, sigar_swap_t *swap)
{
#ifdef VM_SWAPUSAGE /* => 10.4 */
struct xsw_usage sw_usage;
size_t size = sizeof(sw_usage);
int mib[] = { CTL_VM, VM_SWAPUSAGE };
if (sysctl(mib, NMIB(mib), &sw_usage, &size, NULL, 0) != 0) {
return errno;
}
swap->total = sw_usage.xsu_total;
swap->used = sw_usage.xsu_used;
swap->free = sw_usage.xsu_avail;
return SIGAR_OK;
#else
return SIGAR_ENOTIMPL; /* <= 10.3 */
#endif
}
int sigar_swap_get(sigar_t *sigar, sigar_swap_t *swap)
{
int status;
vm_statistics_data_t vmstat;
if (sigar_swap_sysctl_get(sigar, swap) != SIGAR_OK) {
status = sigar_swap_fs_get(sigar, swap); /* <= 10.3 */
if (status != SIGAR_OK) {
return status;
}
}
if ((status = sigar_vmstat(sigar, &vmstat)) != SIGAR_OK) {
return status;
}
swap->page_in = vmstat.pageins;
swap->page_out = vmstat.pageouts;
return SIGAR_OK;
}
#ifndef KERN_CPTIME
#define KERN_CPTIME KERN_CP_TIME
#endif
typedef time_t cp_time_t;
int sigar_cpu_get(sigar_t *sigar, sigar_cpu_t *cpu)
{
kern_return_t status;
mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
host_cpu_load_info_data_t cpuload;
status = host_statistics(sigar->mach_port, HOST_CPU_LOAD_INFO,
(host_info_t)&cpuload, &count);
if (status != KERN_SUCCESS) {
return errno;
}
cpu->user = SIGAR_TICK2MSEC(cpuload.cpu_ticks[CPU_STATE_USER]);
cpu->sys = SIGAR_TICK2MSEC(cpuload.cpu_ticks[CPU_STATE_SYSTEM]);
cpu->idle = SIGAR_TICK2MSEC(cpuload.cpu_ticks[CPU_STATE_IDLE]);
cpu->nice = SIGAR_TICK2MSEC(cpuload.cpu_ticks[CPU_STATE_NICE]);
cpu->wait = 0; /*N/A*/
cpu->irq = 0; /*N/A*/
cpu->soft_irq = 0; /*N/A*/
cpu->stolen = 0; /*N/A*/
cpu->total = cpu->user + cpu->nice + cpu->sys + cpu->idle;
return SIGAR_OK;
}
int sigar_cpu_list_get(sigar_t *sigar, sigar_cpu_list_t *cpulist)
{
kern_return_t status;
mach_msg_type_number_t count;
processor_cpu_load_info_data_t *cpuload;
natural_t i, ncpu;
status = host_processor_info(sigar->mach_port,
PROCESSOR_CPU_LOAD_INFO,
&ncpu,
(processor_info_array_t*)&cpuload,
&count);
if (status != KERN_SUCCESS) {
return errno;
}
sigar_cpu_list_create(cpulist);
for (i=0; i<ncpu; i++) {
sigar_cpu_t *cpu;
SIGAR_CPU_LIST_GROW(cpulist);
cpu = &cpulist->data[cpulist->number++];
cpu->user = SIGAR_TICK2MSEC(cpuload[i].cpu_ticks[CPU_STATE_USER]);
cpu->sys = SIGAR_TICK2MSEC(cpuload[i].cpu_ticks[CPU_STATE_SYSTEM]);
cpu->idle = SIGAR_TICK2MSEC(cpuload[i].cpu_ticks[CPU_STATE_IDLE]);
cpu->nice = SIGAR_TICK2MSEC(cpuload[i].cpu_ticks[CPU_STATE_NICE]);
cpu->wait = 0; /*N/A*/
cpu->irq = 0; /*N/A*/
cpu->soft_irq = 0; /*N/A*/
cpu->stolen = 0; /*N/A*/
cpu->total = cpu->user + cpu->nice + cpu->sys + cpu->idle;
}
vm_deallocate(mach_task_self(), (vm_address_t)cpuload, count);
return SIGAR_OK;
}
int sigar_uptime_get(sigar_t *sigar,
sigar_uptime_t *uptime)
{
uptime->uptime = time(NULL) - sigar->boot_time;
return SIGAR_OK;
}
int sigar_loadavg_get(sigar_t *sigar,
sigar_loadavg_t *loadavg)
{
loadavg->processor_queue = SIGAR_FIELD_NOTIMPL;
getloadavg(loadavg->loadavg, 3);
return SIGAR_OK;
}
int sigar_system_stats_get (sigar_t *sigar,
sigar_system_stats_t *system_stats)
{
return SIGAR_ENOTIMPL;
}
#if defined(DARWIN_HAS_LIBPROC_H)
static int proc_fdinfo_get(sigar_t *sigar, sigar_pid_t pid, int *num)
{
int rsize;
const int init_size = PROC_PIDLISTFD_SIZE * 32;
#ifdef DARWIN_HAS_LIBPROC_H
if (!sigar->libproc) {
return SIGAR_ENOTIMPL;
}
#endif
if (sigar->ifconf_len == 0) {
sigar->ifconf_len = init_size;
sigar->ifconf_buf = malloc(sigar->ifconf_len);
}
while (1) {
rsize = sigar->proc_pidinfo(pid, PROC_PIDLISTFDS, 0,
sigar->ifconf_buf, sigar->ifconf_len);
if (rsize <= 0) {
return errno;
}
if ((rsize + PROC_PIDLISTFD_SIZE) < sigar->ifconf_len) {
break;
}
sigar->ifconf_len += init_size;
sigar->ifconf_buf = realloc(sigar->ifconf_buf, sigar->ifconf_len);
}
*num = rsize / PROC_PIDLISTFD_SIZE;
return SIGAR_OK;
}
#endif
static int proc_fd_get_count(sigar_t *sigar, sigar_pid_t pid, int *num)
{
#if TARGET_OS_IPHONE
return SIGAR_ENOTIMPL;
#else
int pinfo_size;
struct proc_fdinfo *pbuffer;
if (!sigar->libproc) {
return SIGAR_ENOTIMPL;
}
pinfo_size = sigar->proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
if (pinfo_size <= 0) {
return SIGAR_ENOTIMPL;
}
pbuffer = malloc(pinfo_size);
pinfo_size = sigar->proc_pidinfo(pid, PROC_PIDLISTFDS, 0, pbuffer, pinfo_size);
free(pbuffer);
*num = pinfo_size / PROC_PIDLISTFD_SIZE;
return SIGAR_OK;
#endif
}
int sigar_os_proc_list_get(sigar_t *sigar,
sigar_proc_list_t *proclist)
{
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
int i, num;
size_t len;
struct kinfo_proc *proc;
if (sysctl(mib, NMIB(mib), NULL, &len, NULL, 0) < 0) {
return errno;
}
proc = malloc(len);
if (sysctl(mib, NMIB(mib), proc, &len, NULL, 0) < 0) {
free(proc);
return errno;
}
num = len/sizeof(*proc);
for (i=0; i<num; i++) {
if (proc[i].KI_FLAG & P_SYSTEM) {
continue;
}
if (proc[i].KI_PID == 0) {
continue;
}
SIGAR_PROC_LIST_GROW(proclist);
proclist->data[proclist->number++] = proc[i].KI_PID;
}
free(proc);
return SIGAR_OK;
}
static int sigar_get_pinfo(sigar_t *sigar, sigar_pid_t pid)
{
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 0 };
size_t len = sizeof(*sigar->pinfo);
time_t timenow = time(NULL);
mib[3] = pid;
if (sigar->pinfo == NULL) {
sigar->pinfo = malloc(len);
}
if (sigar->last_pid == pid) {
if ((timenow - sigar->last_getprocs) < SIGAR_LAST_PROC_EXPIRE) {
return SIGAR_OK;
}
}
sigar->last_pid = pid;
sigar->last_getprocs = timenow;
if (sysctl(mib, NMIB(mib), sigar->pinfo, &len, NULL, 0) < 0) {
return errno;
}
return SIGAR_OK;
}
#if defined(SHARED_TEXT_REGION_SIZE) && defined(SHARED_DATA_REGION_SIZE)
# define GLOBAL_SHARED_SIZE (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE) /* 10.4 SDK */
#endif
#if defined(DARWIN_HAS_LIBPROC_H) && !defined(GLOBAL_SHARED_SIZE)
/* get the CPU type of the process for the given pid */
static int sigar_proc_cpu_type(sigar_t *sigar, sigar_pid_t pid, cpu_type_t *type)
{
int status;
int mib[CTL_MAXNAME];
size_t len, miblen = NMIB(mib);
status = sysctlnametomib("sysctl.proc_cputype", mib, &miblen);
if (status != SIGAR_OK) {
return status;
}
mib[miblen] = pid;
len = sizeof(*type);
return sysctl(mib, miblen + 1, type, &len, NULL, 0);
}
/* shared memory region size for the given cpu_type_t */
static mach_vm_size_t sigar_shared_region_size(cpu_type_t type)
{
switch (type) {
case CPU_TYPE_ARM:
return SHARED_REGION_SIZE_ARM;
case CPU_TYPE_POWERPC:
return SHARED_REGION_SIZE_PPC;
case CPU_TYPE_POWERPC64:
return SHARED_REGION_SIZE_PPC64;
case CPU_TYPE_I386:
return SHARED_REGION_SIZE_I386;
case CPU_TYPE_X86_64:
return SHARED_REGION_SIZE_X86_64;
default:
return SHARED_REGION_SIZE_I386; /* assume 32-bit x86|ppc */
}
}
#endif
int sigar_proc_mem_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_mem_t *procmem)
{
mach_port_t task, self = mach_task_self();
kern_return_t status;
task_basic_info_data_t info;
task_events_info_data_t events;
mach_msg_type_number_t count;
# ifdef DARWIN_HAS_LIBPROC_H
struct proc_taskinfo pti;
struct proc_regioninfo pri;
if (sigar->libproc) {
int sz =
sigar->proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti));
if (sz == sizeof(pti)) {
procmem->size = pti.pti_virtual_size;
procmem->resident = pti.pti_resident_size;
procmem->page_faults = pti.pti_faults;
procmem->minor_faults = SIGAR_FIELD_NOTIMPL;
procmem->major_faults = SIGAR_FIELD_NOTIMPL;
procmem->share = SIGAR_FIELD_NOTIMPL;
sz = sigar->proc_pidinfo(pid, PROC_PIDREGIONINFO, 0, &pri, sizeof(pri));
if (sz == sizeof(pri)) {
if (pri.pri_share_mode == SM_EMPTY) {
mach_vm_size_t shared_size;
#ifdef GLOBAL_SHARED_SIZE
shared_size = GLOBAL_SHARED_SIZE; /* 10.4 SDK */
#else
cpu_type_t cpu_type;
if (sigar_proc_cpu_type(sigar, pid, &cpu_type) == SIGAR_OK) {
shared_size = sigar_shared_region_size(cpu_type);
}
else {
shared_size = SHARED_REGION_SIZE_I386; /* assume 32-bit x86|ppc */
}
#endif
if (procmem->size > shared_size) {
procmem->size -= shared_size; /* SIGAR-123 */
}
}
}
return SIGAR_OK;
}
}
# endif
status = task_for_pid(self, pid, &task);
if (status != KERN_SUCCESS) {
return errno;
}
count = TASK_BASIC_INFO_COUNT;
status = task_info(task, TASK_BASIC_INFO, (task_info_t)&info, &count);
if (status != KERN_SUCCESS) {
return errno;
}
count = TASK_EVENTS_INFO_COUNT;
status = task_info(task, TASK_EVENTS_INFO, (task_info_t)&events, &count);
if (status == KERN_SUCCESS) {
procmem->page_faults = events.faults;
}
else {
procmem->page_faults = SIGAR_FIELD_NOTIMPL;
}
procmem->minor_faults = SIGAR_FIELD_NOTIMPL;
procmem->major_faults = SIGAR_FIELD_NOTIMPL;
if (task != self) {
mach_port_deallocate(self, task);
}
procmem->size = info.virtual_size;
procmem->resident = info.resident_size;
procmem->share = SIGAR_FIELD_NOTIMPL;
return SIGAR_OK;
}
int sigar_proc_cumulative_disk_io_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_cumulative_disk_io_t *proc_cumulative_disk_io)
{
return SIGAR_ENOTIMPL;
}
int sigar_proc_cred_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_cred_t *proccred)
{
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
if (status != SIGAR_OK) {
return status;
}
proccred->uid = pinfo->KI_UID;
proccred->gid = pinfo->KI_GID;
proccred->euid = pinfo->KI_EUID;
proccred->egid = pinfo->KI_EGID;
return SIGAR_OK;
}
#define tv2msec(tv) \
(((sigar_uint64_t)tv.tv_sec * SIGAR_MSEC) + (((sigar_uint64_t)tv.tv_usec) / 1000))
#define tval2msec(tval) \
((tval.seconds * SIGAR_MSEC) + (tval.microseconds / 1000))
#define tval2nsec(tval) \
(SIGAR_SEC2NANO((tval).seconds) + SIGAR_MICROSEC2NANO((tval).microseconds))
static int get_proc_times(sigar_t *sigar, sigar_pid_t pid, sigar_proc_time_t *time)
{
unsigned int count;
time_value_t utime = {0, 0}, stime = {0, 0};
task_basic_info_data_t ti;
task_thread_times_info_data_t tti;
task_port_t task, self;
kern_return_t status;
# ifdef DARWIN_HAS_LIBPROC_H
if (sigar->libproc) {
struct proc_taskinfo pti;
int sz =
sigar->proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti));
if (sz == sizeof(pti)) {
time->user = SIGAR_NSEC2MSEC(pti.pti_total_user);
time->sys = SIGAR_NSEC2MSEC(pti.pti_total_system);
time->total = time->user + time->sys;
return SIGAR_OK;
}
}
# endif
self = mach_task_self();
status = task_for_pid(self, pid, &task);
if (status != KERN_SUCCESS) {
return errno;
}
count = TASK_BASIC_INFO_COUNT;
status = task_info(task, TASK_BASIC_INFO,
(task_info_t)&ti, &count);
if (status != KERN_SUCCESS) {
if (task != self) {
mach_port_deallocate(self, task);
}
return errno;
}
count = TASK_THREAD_TIMES_INFO_COUNT;
status = task_info(task, TASK_THREAD_TIMES_INFO,
(task_info_t)&tti, &count);
if (status != KERN_SUCCESS) {
if (task != self) {
mach_port_deallocate(self, task);
}
return errno;
}
time_value_add(&utime, &ti.user_time);
time_value_add(&stime, &ti.system_time);
time_value_add(&utime, &tti.user_time);
time_value_add(&stime, &tti.system_time);
time->user = tval2msec(utime);
time->sys = tval2msec(stime);
time->total = time->user + time->sys;
return SIGAR_OK;
}
int sigar_proc_time_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_time_t *proctime)
{
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
if (status != SIGAR_OK) {
return status;
}
if ((status = get_proc_times(sigar, pid, proctime)) != SIGAR_OK) {
return status;
}
proctime->start_time = tv2msec(pinfo->KI_START);
return SIGAR_OK;
}
/* thread state mapping derived from ps.tproj */
static const char thread_states[] = {
/*0*/ '-',
/*1*/ SIGAR_PROC_STATE_RUN,
/*2*/ SIGAR_PROC_STATE_ZOMBIE,
/*3*/ SIGAR_PROC_STATE_SLEEP,
/*4*/ SIGAR_PROC_STATE_IDLE,
/*5*/ SIGAR_PROC_STATE_STOP,
/*6*/ SIGAR_PROC_STATE_STOP,
/*7*/ '?'
};
static int thread_state_get(thread_basic_info_data_t *info)
{
switch (info->run_state) {
case TH_STATE_RUNNING:
return 1;
case TH_STATE_UNINTERRUPTIBLE:
return 2;
case TH_STATE_WAITING:
return (info->sleep_time > 20) ? 4 : 3;
case TH_STATE_STOPPED:
return 5;
case TH_STATE_HALTED:
return 6;
default:
return 7;
}
}
static int sigar_proc_threads_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_state_t *procstate)
{
mach_port_t task, self = mach_task_self();
kern_return_t status;
thread_array_t threads;
mach_msg_type_number_t count, i;
int state = TH_STATE_HALTED + 1;
status = task_for_pid(self, pid, &task);
if (status != KERN_SUCCESS) {
return errno;
}
status = task_threads(task, &threads, &count);
if (status != KERN_SUCCESS) {
return errno;
}
procstate->threads = count;
for (i=0; i<count; i++) {
mach_msg_type_number_t info_count = THREAD_BASIC_INFO_COUNT;
thread_basic_info_data_t info;
status = thread_info(threads[i], THREAD_BASIC_INFO,
(thread_info_t)&info, &info_count);
if (status == KERN_SUCCESS) {
int tstate = thread_state_get(&info);
if (tstate < state) {
state = tstate;
}
}
}
vm_deallocate(self, (vm_address_t)threads, sizeof(thread_t) * count);
procstate->state = thread_states[state];
return SIGAR_OK;
}
int sigar_proc_state_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_state_t *procstate)
{
int status = sigar_get_pinfo(sigar, pid);
bsd_pinfo_t *pinfo = sigar->pinfo;
int state = pinfo->KI_STAT;
if (status != SIGAR_OK) {
return status;
}
procstate->open_files = SIGAR_FIELD_NOTIMPL;
SIGAR_SSTRCPY(procstate->name, pinfo->KI_COMM);
procstate->ppid = pinfo->KI_PPID;
procstate->priority = pinfo->KI_PRI;
procstate->nice = pinfo->KI_NICE;
procstate->tty = SIGAR_FIELD_NOTIMPL; /*XXX*/
procstate->threads = SIGAR_FIELD_NOTIMPL;
procstate->processor = SIGAR_FIELD_NOTIMPL;
int num = 0;
status = proc_fd_get_count(sigar, pid, &num);
if (status == SIGAR_OK) {
procstate->open_files = num;
}
status = sigar_proc_threads_get(sigar, pid, procstate);
if (status == SIGAR_OK) {
return status;
}
switch (state) {
case SIDL:
procstate->state = 'D';
break;
case SRUN:
#ifdef SONPROC
case SONPROC:
#endif
procstate->state = 'R';
break;
case SSLEEP:
procstate->state = 'S';
break;
case SSTOP:
procstate->state = 'T';
break;
case SZOMB:
procstate->state = 'Z';
break;
default:
procstate->state = '?';
break;
}
return SIGAR_OK;
}
typedef struct {
char *buf, *ptr, *end;
int count;
} sigar_kern_proc_args_t;
static void sigar_kern_proc_args_destroy(sigar_kern_proc_args_t *kargs)
{
if (kargs->buf) {
free(kargs->buf);
kargs->buf = NULL;
}
}
/* re-usable hack for use by proc_args and proc_env */
static int sigar_kern_proc_args_get(sigar_t *sigar,
sigar_pid_t pid,
char *exe,
sigar_kern_proc_args_t *kargs)
{
/*
* derived from:
* http://darwinsource.opendarwin.org/10.4.1/adv_cmds-79.1/ps.tproj/print.c
*/
int mib[3], len;
size_t size = sigar_argmax_get(sigar);
kargs->buf = malloc(size);
mib[0] = CTL_KERN;
mib[1] = KERN_PROCARGS2;
mib[2] = pid;
if (sysctl(mib, NMIB(mib), kargs->buf, &size, NULL, 0) < 0) {
sigar_kern_proc_args_destroy(kargs);
return errno;
}
kargs->end = &kargs->buf[size];
memcpy(&kargs->count, kargs->buf, sizeof(kargs->count));
kargs->ptr = kargs->buf + sizeof(kargs->count);
len = strlen(kargs->ptr);
if (exe) {
memcpy(exe, kargs->ptr, len+1);
}
kargs->ptr += len+1;
if (kargs->ptr == kargs->end) {
sigar_kern_proc_args_destroy(kargs);
return exe ? SIGAR_OK : ENOENT;
}
for (; kargs->ptr < kargs->end; kargs->ptr++) {
if (*kargs->ptr != '\0') {
break; /* start of argv[0] */
}
}
if (kargs->ptr == kargs->end) {
sigar_kern_proc_args_destroy(kargs);
return exe ? SIGAR_OK : ENOENT;
}
return SIGAR_OK;
}
static int kern_proc_args_skip_argv(sigar_kern_proc_args_t *kargs)
{
char *ptr = kargs->ptr;
char *end = kargs->end;
int count = kargs->count;
/* skip over argv */
while ((ptr < end) && (count-- > 0)) {
int alen = strlen(ptr)+1;
ptr += alen;
}
kargs->ptr = ptr;
kargs->end = end;
kargs->count = 0;
if (ptr >= end) {
return ENOENT;
}
return SIGAR_OK;
}
int sigar_os_proc_args_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_args_t *procargs)
{
int status, count;
sigar_kern_proc_args_t kargs;
char *ptr, *end;
status = sigar_kern_proc_args_get(sigar, pid, NULL, &kargs);
if (status != SIGAR_OK) {
return status;
}
count = kargs.count;
ptr = kargs.ptr;
end = kargs.end;
while ((ptr < end) && (count-- > 0)) {
int slen = strlen(ptr);
int alen = slen+1;
char *arg;
/*
* trim trailing whitespace.
* seen w/ postgresql, probably related
* to messing with argv[0]
*/
while (*(ptr + (slen-1)) == ' ') {
if (--slen <= 0) {
break;
}
}
arg = malloc(slen+1);
SIGAR_PROC_ARGS_GROW(procargs);
memcpy(arg, ptr, slen);
*(arg+slen) = '\0';
procargs->data[procargs->number++] = arg;
ptr += alen;
}
sigar_kern_proc_args_destroy(&kargs);
return SIGAR_OK;
}
int sigar_proc_env_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_env_t *procenv)
{
int status, count;
sigar_kern_proc_args_t kargs;
char *ptr, *end;
status = sigar_kern_proc_args_get(sigar, pid, NULL, &kargs);
if (status != SIGAR_OK) {
return status;
}
status = kern_proc_args_skip_argv(&kargs);
if (status != SIGAR_OK) {
sigar_kern_proc_args_destroy(&kargs);
return status;
}
count = kargs.count;
ptr = kargs.ptr;
end = kargs.end;
/* into environ */
while (ptr < end) {
char *val = strchr(ptr, '=');
int klen, vlen, status;
char key[256]; /* XXX is there a max key size? */
if (val == NULL) {
/* not key=val format */
break;
}
klen = val - ptr;
SIGAR_SSTRCPY(key, ptr);
key[klen] = '\0';
++val;
vlen = strlen(val);
status = procenv->env_getter(procenv->data,
key, klen, val, vlen);
if (status != SIGAR_OK) {
/* not an error; just stop iterating */
break;
}
ptr += (klen + 1 + vlen + 1);
if (*ptr == '\0') {
break;
}
}
sigar_kern_proc_args_destroy(&kargs);
return SIGAR_OK;
}
int sigar_proc_fd_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_fd_t *procfd)
{
return SIGAR_ENOTIMPL;
}
int sigar_proc_exe_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_exe_t *procexe)
{
memset(procexe, 0, sizeof(*procexe));
int status;
sigar_kern_proc_args_t kargs;
status = sigar_kern_proc_args_get(sigar, pid, procexe->name, &kargs);
if (status == SIGAR_OK) {
/* attempt to determine cwd from $PWD */
status = kern_proc_args_skip_argv(&kargs);
if (status == SIGAR_OK) {
char *ptr = kargs.ptr;
char *end = kargs.end;
/* into environ */
while (ptr < end) {
int len = strlen(ptr);
if ((len > 4) &&
(ptr[0] == 'P') &&
(ptr[1] == 'W') &&
(ptr[2] == 'D') &&
(ptr[3] == '='))
{
memcpy(procexe->cwd, ptr+4, len-3);
break;
}
ptr += len+1;
}
}
sigar_kern_proc_args_destroy(&kargs);
}
// XXX do we need to read mach-o, or is there a better way?
procexe->arch = sigar->arch;
return SIGAR_OK;
}
static int sigar_dlinfo_modules(sigar_t *sigar, sigar_proc_modules_t *procmods)
{
uint32_t i, count = _dyld_image_count();
for (i=0; i<count; i++) {
int status;
const char *name =
_dyld_get_image_name(i);
if (name == NULL) {
continue;
}
status =
procmods->module_getter(procmods->data,
(char *)name, strlen(name));
if (status != SIGAR_OK) {
/* not an error; just stop iterating */
break;
}
}
return SIGAR_OK;
}
int sigar_proc_modules_get(sigar_t *sigar, sigar_pid_t pid,
sigar_proc_modules_t *procmods)
{
if (pid == sigar_pid_get(sigar)) {
return sigar_dlinfo_modules(sigar, procmods);
}
return SIGAR_ENOTIMPL;
}
#define SIGAR_MICROSEC2NANO(s) \
((sigar_uint64_t)(s) * (sigar_uint64_t)1000)
#define TIME_NSEC(t) \
(SIGAR_SEC2NANO((t).tv_sec) + SIGAR_MICROSEC2NANO((t).tv_usec))
int sigar_thread_cpu_get(sigar_t *sigar,
sigar_uint64_t id,
sigar_thread_cpu_t *cpu)
{
mach_port_t self = mach_thread_self();
thread_basic_info_data_t info;
mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
kern_return_t status;
status = thread_info(self, THREAD_BASIC_INFO,
(thread_info_t)&info, &count);
if (status != KERN_SUCCESS) {
return errno;
}
mach_port_deallocate(mach_task_self(), self);
cpu->user = tval2nsec(info.user_time);
cpu->sys = tval2nsec(info.system_time);
cpu->total = cpu->user + cpu->sys;
return SIGAR_OK;
}
int sigar_os_fs_type_get(sigar_file_system_t *fsp)
{
char *type = fsp->sys_type_name;
/* see sys/disklabel.h */
switch (*type) {
case 'f':
if (strEQ(type, "ffs")) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
}
break;
case 'h':
if (strEQ(type, "hfs")) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
}
break;
case 'u':
if (strEQ(type, "ufs")) {
fsp->type = SIGAR_FSTYPE_LOCAL_DISK;
}
break;
}
return fsp->type;
}
static void get_fs_options(char *opts, int osize, long flags)
{
*opts = '\0';
if (flags & MNT_RDONLY) strncat(opts, "ro", osize);
else strncat(opts, "rw", osize);
if (flags & MNT_SYNCHRONOUS) strncat(opts, ",sync", osize);
if (flags & MNT_NOEXEC) strncat(opts, ",noexec", osize);
if (flags & MNT_NOSUID) strncat(opts, ",nosuid", osize);
#ifdef MNT_NODEV
if (flags & MNT_NODEV) strncat(opts, ",nodev", osize);
#endif
#ifdef MNT_UNION
if (flags & MNT_UNION) strncat(opts, ",union", osize);
#endif
if (flags & MNT_ASYNC) strncat(opts, ",async", osize);
#ifdef MNT_NOATIME
if (flags & MNT_NOATIME) strncat(opts, ",noatime", osize);
#endif
#ifdef MNT_NOCLUSTERR
if (flags & MNT_NOCLUSTERR) strncat(opts, ",noclusterr", osize);
#endif
#ifdef MNT_NOCLUSTERW
if (flags & MNT_NOCLUSTERW) strncat(opts, ",noclusterw", osize);
#endif
#ifdef MNT_NOSYMFOLLOW
if (flags & MNT_NOSYMFOLLOW) strncat(opts, ",nosymfollow", osize);
#endif
#ifdef MNT_SUIDDIR
if (flags & MNT_SUIDDIR) strncat(opts, ",suiddir", osize);
#endif
#ifdef MNT_SOFTDEP
if (flags & MNT_SOFTDEP) strncat(opts, ",soft-updates", osize);
#endif
if (flags & MNT_LOCAL) strncat(opts, ",local", osize);
if (flags & MNT_QUOTA) strncat(opts, ",quota", osize);
if (flags & MNT_ROOTFS) strncat(opts, ",rootfs", osize);
#ifdef MNT_USER
if (flags & MNT_USER) strncat(opts, ",user", osize);
#endif
#ifdef MNT_IGNORE
if (flags & MNT_IGNORE) strncat(opts, ",ignore", osize);
#endif
if (flags & MNT_EXPORTED) strncat(opts, ",nfs", osize);
}
#define sigar_statfs statfs
#define sigar_getfsstat getfsstat
#define sigar_f_flags f_flags
int sigar_file_system_list_get(sigar_t *sigar,
sigar_file_system_list_t *fslist)
{
struct sigar_statfs *fs;
int num, i;
int is_debug = SIGAR_LOG_IS_DEBUG(sigar);
long len;
if ((num = sigar_getfsstat(NULL, 0, MNT_NOWAIT)) < 0) {
return errno;
}
len = sizeof(*fs) * num;
fs = malloc(len);
if ((num = sigar_getfsstat(fs, len, MNT_NOWAIT)) < 0) {
free(fs);
return errno;
}
sigar_file_system_list_create(fslist);
for (i=0; i<num; i++) {
sigar_file_system_t *fsp;
#ifdef MNT_AUTOMOUNTED
if (fs[i].sigar_f_flags & MNT_AUTOMOUNTED) {
if (is_debug) {
sigar_log_printf(sigar, SIGAR_LOG_DEBUG,
"[file_system_list] skipping automounted %s: %s",
fs[i].f_fstypename, fs[i].f_mntonname);
}
continue;
}
#endif
#ifdef MNT_RDONLY
if (fs[i].sigar_f_flags & MNT_RDONLY) {
/* e.g. ftp mount or .dmg image */
if (is_debug) {
sigar_log_printf(sigar, SIGAR_LOG_DEBUG,
"[file_system_list] skipping readonly %s: %s",
fs[i].f_fstypename, fs[i].f_mntonname);
}
continue;
}
#endif
SIGAR_FILE_SYSTEM_LIST_GROW(fslist);
fsp = &fslist->data[fslist->number++];
SIGAR_SSTRCPY(fsp->dir_name, fs[i].f_mntonname);
SIGAR_SSTRCPY(fsp->dev_name, fs[i].f_mntfromname);
SIGAR_SSTRCPY(fsp->sys_type_name, fs[i].f_fstypename);
get_fs_options(fsp->options, sizeof(fsp->options)-1, fs[i].sigar_f_flags);
sigar_fs_type_init(fsp);
}
free(fs);
return SIGAR_OK;
}
#define IoStatGetValue(key, val) \
if ((number = (CFNumberRef)CFDictionaryGetValue(stats, CFSTR(kIOBlockStorageDriverStatistics##key)))) \
CFNumberGetValue(number, kCFNumberSInt64Type, &val)
int sigar_disk_usage_get(sigar_t *sigar, const char *name,
sigar_disk_usage_t *disk)
{
#if TARGET_OS_IPHONE
return SIGAR_ENOTIMPL;
#else
kern_return_t status;
io_registry_entry_t parent;
io_service_t service;
CFDictionaryRef props;
CFNumberRef number;
sigar_iodev_t *iodev = sigar_iodev_get(sigar, name);
char dname[256], *ptr;
SIGAR_DISK_STATS_INIT(disk);
if (!iodev) {
return ENXIO;
}
/* "/dev/disk0s1" -> "disk0" */ /* XXX better way? */
ptr = &iodev->name[SSTRLEN(SIGAR_DEV_PREFIX)];
SIGAR_SSTRCPY(dname, ptr);
ptr = dname;
if (strnEQ(ptr, "disk", 4)) {
ptr += 4;
if ((ptr = strchr(ptr, 's')) && isdigit(*(ptr+1))) {
*ptr = '\0';
}
}
if (SIGAR_LOG_IS_DEBUG(sigar)) {
sigar_log_printf(sigar, SIGAR_LOG_DEBUG,
"[disk_usage] map %s -> %s",
iodev->name, dname);
}
/* e.g. name == "disk0" */
service = IOServiceGetMatchingService(kIOMasterPortDefault,
IOBSDNameMatching(kIOMasterPortDefault, 0, dname));
if (!service) {
return errno;
}
status = IORegistryEntryGetParentEntry(service, kIOServicePlane, &parent);
if (status != KERN_SUCCESS) {
IOObjectRelease(service);
return status;
}
status = IORegistryEntryCreateCFProperties(parent,
(CFMutableDictionaryRef *)&props,
kCFAllocatorDefault,
kNilOptions);
if (props) {
CFDictionaryRef stats =
(CFDictionaryRef)CFDictionaryGetValue(props,
CFSTR(kIOBlockStorageDriverStatisticsKey));
if (stats) {
IoStatGetValue(ReadsKey, disk->reads);
IoStatGetValue(BytesReadKey, disk->read_bytes);
IoStatGetValue(TotalReadTimeKey, disk->rtime);
IoStatGetValue(WritesKey, disk->writes);
IoStatGetValue(BytesWrittenKey, disk->write_bytes);
IoStatGetValue(TotalWriteTimeKey, disk->wtime);
disk->time = disk->rtime + disk->wtime;
}
CFRelease(props);
}
IOObjectRelease(service);
IOObjectRelease(parent);
return SIGAR_OK;
#endif
}
int sigar_file_system_usage_get(sigar_t *sigar,
const char *dirname,
sigar_file_system_usage_t *fsusage)
{
int status = sigar_statvfs(sigar, dirname, fsusage);
if (status != SIGAR_OK) {
return status;
}
fsusage->use_percent = sigar_file_system_usage_calc_used(sigar, fsusage);
sigar_disk_usage_get(sigar, dirname, &fsusage->disk);
return SIGAR_OK;
}
#define CTL_HW_FREQ_MAX "hw.cpufrequency_max"
#define CTL_HW_FREQ_MIN "hw.cpufrequency_min"
int sigar_cpu_info_list_get(sigar_t *sigar,
sigar_cpu_info_list_t *cpu_infos)
{
int i;
unsigned int mhz, mhz_min, mhz_max;
int cache_size=SIGAR_FIELD_NOTIMPL;
size_t size;
char model[128], vendor[128], *ptr;
size = sizeof(mhz);
(void)sigar_cpu_core_count(sigar);
{
int mib[] = { CTL_HW, HW_CPU_FREQ };
size = sizeof(mhz);
if (sysctl(mib, NMIB(mib), &mhz, &size, NULL, 0) < 0) {
mhz = SIGAR_FIELD_NOTIMPL;
}
}
if (sysctlbyname(CTL_HW_FREQ_MAX, &mhz_max, &size, NULL, 0) < 0) {
mhz_max = SIGAR_FIELD_NOTIMPL;
}
if (sysctlbyname(CTL_HW_FREQ_MIN, &mhz_min, &size, NULL, 0) < 0) {
mhz_min = SIGAR_FIELD_NOTIMPL;
}
if (mhz != SIGAR_FIELD_NOTIMPL) {
mhz /= 1000000;
}
if (mhz_max != SIGAR_FIELD_NOTIMPL) {
mhz_max /= 1000000;
}
if (mhz_min != SIGAR_FIELD_NOTIMPL) {
mhz_min /= 1000000;
}
size = sizeof(model);
if (sysctlbyname("hw.model", &model, &size, NULL, 0) < 0) {
int mib[] = { CTL_HW, HW_MODEL };
size = sizeof(model);
if (sysctl(mib, NMIB(mib), &model[0], &size, NULL, 0) < 0) {
strcpy(model, "Unknown");
}
}
if (mhz == SIGAR_FIELD_NOTIMPL) {
/* freebsd4 */
mhz = sigar_cpu_mhz_from_model(model);
}
/* XXX not sure */
if (mhz_max == SIGAR_FIELD_NOTIMPL) {
mhz_max = 0;
}
if (mhz_min == SIGAR_FIELD_NOTIMPL) {
mhz_min = 0;
}
size = sizeof(vendor);
if (sysctlbyname("machdep.cpu.vendor", &vendor, &size, NULL, 0) < 0) {
SIGAR_SSTRCPY(vendor, "Apple");
}
else {
/* GenuineIntel -> Intel */
if (strstr(vendor, "Intel")) {
SIGAR_SSTRCPY(vendor, "Intel");
}
}
if ((ptr = strchr(model, ' '))) {
if (strstr(model, "Intel")) {
SIGAR_SSTRCPY(vendor, "Intel");
}
else if (strstr(model, "AMD")) {
SIGAR_SSTRCPY(vendor, "AMD");
}
else {
SIGAR_SSTRCPY(vendor, "Unknown");
}
SIGAR_SSTRCPY(model, ptr+1);
}
{
int mib[] = { CTL_HW, HW_L2CACHESIZE }; /* in bytes */
size = sizeof(cache_size);
if (sysctl(mib, NMIB(mib), &cache_size, &size, NULL, 0) < 0) {
cache_size = SIGAR_FIELD_NOTIMPL;
}
else {
cache_size /= 1024; /* convert to KB */
}
}
sigar_cpu_info_list_create(cpu_infos);
for (i=0; i<sigar->ncpu; i++) {
sigar_cpu_info_t *info;
SIGAR_CPU_INFO_LIST_GROW(cpu_infos);
info = &cpu_infos->data[cpu_infos->number++];
SIGAR_SSTRCPY(info->vendor, vendor);
SIGAR_SSTRCPY(info->model, model);
sigar_cpu_model_adjust(sigar, info);
info->mhz = mhz;
info->mhz_max = mhz_max;
info->mhz_min = mhz_min;
info->cache_size = cache_size;
info->total_cores = sigar->ncpu;
info->cores_per_socket = sigar->lcpu;
info->total_sockets = sigar_cpu_socket_count(sigar);
}
return SIGAR_OK;
}
#define rt_s_addr(sa) ((struct sockaddr_in *)(sa))->sin_addr.s_addr
#ifndef SA_SIZE
#define SA_SIZE(sa) \
( (!(sa) || ((struct sockaddr *)(sa))->sa_len == 0) ? \
sizeof(long) : \
1 + ( (((struct sockaddr *)(sa))->sa_len - 1) | (sizeof(long) - 1) ) )
#endif
int sigar_net_route_list_get(sigar_t *sigar,
sigar_net_route_list_t *routelist)
{
#if TARGET_OS_IPHONE
return SIGAR_ENOTIMPL;
#else
size_t needed;
int bit;
char *buf, *next, *lim;
struct rt_msghdr *rtm;
int mib[6] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_DUMP, 0 };
if (sysctl(mib, NMIB(mib), NULL, &needed, NULL, 0) < 0) {
return errno;
}
buf = malloc(needed);
if (sysctl(mib, NMIB(mib), buf, &needed, NULL, 0) < 0) {
free(buf);
return errno;
}
sigar_net_route_list_create(routelist);
lim = buf + needed;
for (next = buf; next < lim; next += rtm->rtm_msglen) {
struct sockaddr *sa;
sigar_net_route_t *route;
rtm = (struct rt_msghdr *)next;
if (rtm->rtm_type != RTM_GET) {
continue;
}
sa = (struct sockaddr *)(rtm + 1);
if (sa->sa_family != AF_INET) {
continue;
}
SIGAR_NET_ROUTE_LIST_GROW(routelist);
route = &routelist->data[routelist->number++];
SIGAR_ZERO(route);
route->flags = rtm->rtm_flags;
if_indextoname(rtm->rtm_index, route->ifname);
for (bit=RTA_DST;
bit && ((char *)sa < lim);
bit <<= 1)
{
if ((rtm->rtm_addrs & bit) == 0) {
continue;
}
switch (bit) {
case RTA_DST:
sigar_net_address_set(route->destination,
rt_s_addr(sa));
break;
case RTA_GATEWAY:
if (sa->sa_family == AF_INET) {
sigar_net_address_set(route->gateway,
rt_s_addr(sa));
}
break;
case RTA_NETMASK:
sigar_net_address_set(route->mask,
rt_s_addr(sa));
break;
case RTA_IFA:
break;
}
sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
}
}
free(buf);
return SIGAR_OK;
#endif
}
typedef enum {
IFMSG_ITER_LIST,
IFMSG_ITER_GET
} ifmsg_iter_e;
typedef struct {
const char *name;
ifmsg_iter_e type;
union {
sigar_net_interface_list_t *iflist;
struct if_msghdr *ifm;
} data;
} ifmsg_iter_t;
static int sigar_ifmsg_init(sigar_t *sigar)
{
int mib[] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_IFLIST, 0 };
size_t len;
if (sysctl(mib, NMIB(mib), NULL, &len, NULL, 0) < 0) {
return errno;
}
if (sigar->ifconf_len < len) {
sigar->ifconf_buf = realloc(sigar->ifconf_buf, len);
sigar->ifconf_len = len;
}
if (sysctl(mib, NMIB(mib), sigar->ifconf_buf, &len, NULL, 0) < 0) {
return errno;
}
return SIGAR_OK;
}
/**
* @param name name of the interface
* @param name_len length of name (w/o \0)
*/
static int has_ifaddr(char *name, size_t name_len)
{
int sock, status;
struct ifreq ifr;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return errno;
}
strncpy(ifr.ifr_name, name, MIN(sizeof(ifr.ifr_name) - 1, name_len));
ifr.ifr_name[MIN(sizeof(ifr.ifr_name) - 1, name_len)] = '\0';
if (ioctl(sock, SIOCGIFADDR, &ifr) == 0) {
status = SIGAR_OK;
}
else {
status = errno;
}
close(sock);
return status;
}
static int sigar_ifmsg_iter(sigar_t *sigar, ifmsg_iter_t *iter)
{
char *end = sigar->ifconf_buf + sigar->ifconf_len;
char *ptr = sigar->ifconf_buf;
if (iter->type == IFMSG_ITER_LIST) {
sigar_net_interface_list_create(iter->data.iflist);
}
while (ptr < end) {
char *name;
struct sockaddr_dl *sdl;
struct if_msghdr *ifm = (struct if_msghdr *)ptr;
if (ifm->ifm_type != RTM_IFINFO) {
break;
}
ptr += ifm->ifm_msglen;
while (ptr < end) {
struct if_msghdr *next = (struct if_msghdr *)ptr;
if (next->ifm_type != RTM_NEWADDR) {
break;
}
ptr += next->ifm_msglen;
}
sdl = (struct sockaddr_dl *)(ifm + 1);
if (sdl->sdl_family != AF_LINK) {
continue;
}
switch (iter->type) {
case IFMSG_ITER_LIST:
if (sdl->sdl_type == IFT_OTHER) {
if (has_ifaddr(sdl->sdl_data, sdl->sdl_nlen) != SIGAR_OK) {
break;
}
}
else if (!((sdl->sdl_type == IFT_ETHER) ||
(sdl->sdl_type == IFT_LOOP)))
{
break; /* XXX deal w/ other weirdo interfaces */
}
SIGAR_NET_IFLIST_GROW(iter->data.iflist);
/* sdl_data doesn't include a trailing \0, it is only sdl_nlen long */
name = malloc(sdl->sdl_nlen+1);
memcpy(name, sdl->sdl_data, sdl->sdl_nlen);
name[sdl->sdl_nlen] = '\0'; /* add the missing \0 */
iter->data.iflist->data[iter->data.iflist->number++] = name;
break;
case IFMSG_ITER_GET:
if (strlen(iter->name) == sdl->sdl_nlen && 0 == memcmp(iter->name, sdl->sdl_data, sdl->sdl_nlen)) {
iter->data.ifm = ifm;
return SIGAR_OK;
}
}
}
switch (iter->type) {
case IFMSG_ITER_LIST:
return SIGAR_OK;
case IFMSG_ITER_GET:
default:
return ENXIO;
}
}
int sigar_net_interface_list_get(sigar_t *sigar,
sigar_net_interface_list_t *iflist)
{
int status;
ifmsg_iter_t iter;
if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) {
return status;
}
iter.type = IFMSG_ITER_LIST;
iter.data.iflist = iflist;
return sigar_ifmsg_iter(sigar, &iter);
}
#include <ifaddrs.h>
/* in6_prefixlen derived from freebsd/sbin/ifconfig/af_inet6.c */
static int sigar_in6_prefixlen(struct sockaddr *netmask)
{
struct in6_addr *addr = SIGAR_SIN6_ADDR(netmask);
u_char *name = (u_char *)addr;
int size = sizeof(*addr);
int byte, bit, plen = 0;
for (byte = 0; byte < size; byte++, plen += 8) {
if (name[byte] != 0xff) {
break;
}
}
if (byte == size) {
return plen;
}
for (bit = 7; bit != 0; bit--, plen++) {
if (!(name[byte] & (1 << bit))) {
break;
}
}
for (; bit != 0; bit--) {
if (name[byte] & (1 << bit)) {
return 0;
}
}
byte++;
for (; byte < size; byte++) {
if (name[byte]) {
return 0;
}
}
return plen;
}
int sigar_net_interface_ipv6_config_get(sigar_t *sigar, const char *name,
sigar_net_interface_config_t *ifconfig)
{
int status = SIGAR_ENOENT;
struct ifaddrs *addrs, *ifa;
if (getifaddrs(&addrs) != 0) {
return errno;
}
for (ifa=addrs; ifa; ifa=ifa->ifa_next) {
if (ifa->ifa_addr &&
(ifa->ifa_addr->sa_family == AF_INET6) &&
strEQ(ifa->ifa_name, name))
{
status = SIGAR_OK;
break;
}
}
if (status == SIGAR_OK) {
struct in6_addr *addr = SIGAR_SIN6_ADDR(ifa->ifa_addr);
sigar_net_address6_set(ifconfig->address6, addr);
sigar_net_interface_scope6_set(ifconfig, addr);
ifconfig->prefix6_length = sigar_in6_prefixlen(ifa->ifa_netmask);
}
freeifaddrs(addrs);
return status;
}
int sigar_net_interface_config_get(sigar_t *sigar, const char *name,
sigar_net_interface_config_t *ifconfig)
{
int sock;
int status;
ifmsg_iter_t iter;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
struct ifreq ifr;
if (!name) {
return sigar_net_interface_config_primary_get(sigar, ifconfig);
}
if (sigar->ifconf_len == 0) {
if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) {
return status;
}
}
SIGAR_ZERO(ifconfig);
iter.type = IFMSG_ITER_GET;
iter.name = name;
if ((status = sigar_ifmsg_iter(sigar, &iter)) != SIGAR_OK) {
return status;
}
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return errno;
}
ifm = iter.data.ifm;
SIGAR_SSTRCPY(ifconfig->name, name);
sdl = (struct sockaddr_dl *)(ifm + 1);
sigar_net_address_mac_set(ifconfig->hwaddr,
LLADDR(sdl),
sdl->sdl_alen);
ifconfig->flags = ifm->ifm_flags;
ifconfig->mtu = ifm->ifm_data.ifi_mtu;
ifconfig->metric = ifm->ifm_data.ifi_metric;
SIGAR_SSTRCPY(ifr.ifr_name, name);
#define ifr_s_addr(ifr) \
((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr
if (!ioctl(sock, SIOCGIFADDR, &ifr)) {
sigar_net_address_set(ifconfig->address,
ifr_s_addr(ifr));
}
if (!ioctl(sock, SIOCGIFNETMASK, &ifr)) {
sigar_net_address_set(ifconfig->netmask,
ifr_s_addr(ifr));
}
if (ifconfig->flags & IFF_LOOPBACK) {
sigar_net_address_set(ifconfig->destination,
ifconfig->address.addr.in);
sigar_net_address_set(ifconfig->broadcast, 0);
SIGAR_SSTRCPY(ifconfig->type,
SIGAR_NIC_LOOPBACK);
}
else {
if (!ioctl(sock, SIOCGIFDSTADDR, &ifr)) {
sigar_net_address_set(ifconfig->destination,
ifr_s_addr(ifr));
}
if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) {
sigar_net_address_set(ifconfig->broadcast,
ifr_s_addr(ifr));
}
SIGAR_SSTRCPY(ifconfig->type,
SIGAR_NIC_ETHERNET);
}
close(sock);
/* XXX can we get a better description like win32? */
SIGAR_SSTRCPY(ifconfig->description,
ifconfig->name);
sigar_net_interface_ipv6_config_init(ifconfig);
sigar_net_interface_ipv6_config_get(sigar, name, ifconfig);
return SIGAR_OK;
}
int sigar_net_interface_stat_get(sigar_t *sigar, const char *name,
sigar_net_interface_stat_t *ifstat)
{
int status;
ifmsg_iter_t iter;
struct if_msghdr *ifm;
if ((status = sigar_ifmsg_init(sigar)) != SIGAR_OK) {
return status;
}
iter.type = IFMSG_ITER_GET;
iter.name = name;
if ((status = sigar_ifmsg_iter(sigar, &iter)) != SIGAR_OK) {
return status;
}
ifm = iter.data.ifm;
ifstat->rx_bytes = ifm->ifm_data.ifi_ibytes;
ifstat->rx_packets = ifm->ifm_data.ifi_ipackets;
ifstat->rx_errors = ifm->ifm_data.ifi_ierrors;
ifstat->rx_dropped = ifm->ifm_data.ifi_iqdrops;
ifstat->rx_overruns = SIGAR_FIELD_NOTIMPL;
ifstat->rx_frame = SIGAR_FIELD_NOTIMPL;
ifstat->tx_bytes = ifm->ifm_data.ifi_obytes;
ifstat->tx_packets = ifm->ifm_data.ifi_opackets;
ifstat->tx_errors = ifm->ifm_data.ifi_oerrors;
ifstat->tx_collisions = ifm->ifm_data.ifi_collisions;
ifstat->tx_dropped = SIGAR_FIELD_NOTIMPL;
ifstat->tx_overruns = SIGAR_FIELD_NOTIMPL;
ifstat->tx_carrier = SIGAR_FIELD_NOTIMPL;
ifstat->speed = ifm->ifm_data.ifi_baudrate;
return SIGAR_OK;
}
static int net_connection_state_get(int state)
{
switch (state) {
case TCPS_CLOSED:
return SIGAR_TCP_CLOSE;
case TCPS_LISTEN:
return SIGAR_TCP_LISTEN;
case TCPS_SYN_SENT:
return SIGAR_TCP_SYN_SENT;
case TCPS_SYN_RECEIVED:
return SIGAR_TCP_SYN_RECV;
case TCPS_ESTABLISHED:
return SIGAR_TCP_ESTABLISHED;
case TCPS_CLOSE_WAIT:
return SIGAR_TCP_CLOSE_WAIT;
case TCPS_FIN_WAIT_1:
return SIGAR_TCP_FIN_WAIT1;
case TCPS_CLOSING:
return SIGAR_TCP_CLOSING;
case TCPS_LAST_ACK:
return SIGAR_TCP_LAST_ACK;
case TCPS_FIN_WAIT_2:
return SIGAR_TCP_FIN_WAIT2;
case TCPS_TIME_WAIT:
return SIGAR_TCP_TIME_WAIT;
default:
return SIGAR_TCP_UNKNOWN;
}
}
static int net_connection_get(sigar_net_connection_walker_t *walker, int proto)
{
int flags = walker->flags;
int type, istcp = 0;
char *buf;
const char *mibvar;
struct tcpcb *tp = NULL;
struct inpcb *inp;
struct xinpgen *xig, *oxig;
struct xsocket *so;
size_t len;
switch (proto) {
case IPPROTO_TCP:
mibvar = "net.inet.tcp.pcblist";
istcp = 1;
type = SIGAR_NETCONN_TCP;
break;
case IPPROTO_UDP:
mibvar = "net.inet.udp.pcblist";
type = SIGAR_NETCONN_UDP;
break;
default:
mibvar = "net.inet.raw.pcblist";
type = SIGAR_NETCONN_RAW;
break;
}
len = 0;
if (sysctlbyname(mibvar, 0, &len, 0, 0) < 0) {
return errno;
}
if ((buf = malloc(len)) == 0) {
return errno;
}
if (sysctlbyname(mibvar, buf, &len, 0, 0) < 0) {
free(buf);
return errno;
}
oxig = xig = (struct xinpgen *)buf;
for (xig = (struct xinpgen *)((char *)xig + xig->xig_len);
xig->xig_len > sizeof(struct xinpgen);
xig = (struct xinpgen *)((char *)xig + xig->xig_len))
{
if (istcp) {
struct xtcpcb *cb = (struct xtcpcb *)xig;
tp = &cb->xt_tp;
inp = &cb->xt_inp;
so = &cb->xt_socket;
}
else {
struct xinpcb *cb = (struct xinpcb *)xig;
inp = &cb->xi_inp;
so = &cb->xi_socket;
}
if (so->xso_protocol != proto) {
continue;
}
if (inp->inp_gencnt > oxig->xig_gen) {
continue;
}
if ((((flags & SIGAR_NETCONN_SERVER) && so->so_qlimit) ||
((flags & SIGAR_NETCONN_CLIENT) && !so->so_qlimit)))
{
sigar_net_connection_t conn;
SIGAR_ZERO(&conn);
if (inp->inp_vflag & INP_IPV6) {
sigar_net_address6_set(conn.local_address,
&inp->in6p_laddr.s6_addr);
sigar_net_address6_set(conn.remote_address,
&inp->in6p_faddr.s6_addr);
}
else {
sigar_net_address_set(conn.local_address,
inp->inp_laddr.s_addr);
sigar_net_address_set(conn.remote_address,
inp->inp_faddr.s_addr);
}
conn.local_port = ntohs(inp->inp_lport);
conn.remote_port = ntohs(inp->inp_fport);
conn.receive_queue = so->so_rcv.sb_cc;
conn.send_queue = so->so_snd.sb_cc;
conn.uid = so->so_pgid;
conn.type = type;
if (!istcp) {
conn.state = SIGAR_TCP_UNKNOWN;
if (walker->add_connection(walker, &conn) != SIGAR_OK) {
break;
}
continue;
}
conn.state = net_connection_state_get(tp->t_state);
if (walker->add_connection(walker, &conn) != SIGAR_OK) {
break;
}
}
}
free(buf);
return SIGAR_OK;
}
int sigar_net_connection_walk(sigar_net_connection_walker_t *walker)
{
int flags = walker->flags;
int status;
if (flags & SIGAR_NETCONN_TCP) {
status = net_connection_get(walker, IPPROTO_TCP);
if (status != SIGAR_OK) {
return status;
}
}
if (flags & SIGAR_NETCONN_UDP) {
status = net_connection_get(walker, IPPROTO_UDP);
if (status != SIGAR_OK) {
return status;
}
}
return SIGAR_OK;
}
SIGAR_DECLARE(int)
sigar_net_listeners_get(sigar_net_connection_walker_t *walker)
{
int status;
status = sigar_net_connection_walk(walker);
if (status != SIGAR_OK) {
return status;
}
#if defined(DARWIN_HAS_LIBPROC_H)
int i;
sigar_net_connection_list_t *list = walker->data;
sigar_pid_t pid;
for (i = 0; i < list->number; i++) {
status = sigar_proc_port_get(walker->sigar, walker->flags,
list->data[i].local_port, &pid);
if (status == SIGAR_OK) {
list->data[i].pid = pid;
}
}
#endif
return SIGAR_OK;
}
SIGAR_DECLARE(int)
sigar_tcp_get(sigar_t *sigar,
sigar_tcp_t *tcp)
{
struct tcpstat mib;
int var[4] = { CTL_NET, PF_INET, IPPROTO_TCP, TCPCTL_STATS };
size_t len = sizeof(mib);
if (sysctl(var, NMIB(var), &mib, &len, NULL, 0) < 0) {
return errno;
}
tcp->active_opens = mib.tcps_connattempt;
tcp->passive_opens = mib.tcps_accepts;
tcp->attempt_fails = mib.tcps_conndrops;
tcp->estab_resets = mib.tcps_drops;
if (sigar_tcp_curr_estab(sigar, tcp) != SIGAR_OK) {
tcp->curr_estab = -1;
}
tcp->in_segs = mib.tcps_rcvtotal;
tcp->out_segs = mib.tcps_sndtotal - mib.tcps_sndrexmitpack;
tcp->retrans_segs = mib.tcps_sndrexmitpack;
tcp->in_errs =
mib.tcps_rcvbadsum +
mib.tcps_rcvbadoff +
mib.tcps_rcvmemdrop +
mib.tcps_rcvshort;
tcp->out_rsts = -1; /* XXX mib.tcps_sndctrl - mib.tcps_closed; ? */
return SIGAR_OK;
}
#if !TARGET_OS_IPHONE
static int get_nfsstats(struct nfsstats *stats)
{
size_t len = sizeof(*stats);
int mib[] = { CTL_VFS, 2, NFS_NFSSTATS };
if (sysctl(mib, NMIB(mib), stats, &len, NULL, 0) < 0) {
return errno;
}
else {
return SIGAR_OK;
}
}
typedef uint64_t rpc_cnt_t;
static void map_nfs_stats(sigar_nfs_v3_t *nfs, rpc_cnt_t *rpc)
{
nfs->null = rpc[NFSPROC_NULL];
nfs->getattr = rpc[NFSPROC_GETATTR];
nfs->setattr = rpc[NFSPROC_SETATTR];
nfs->lookup = rpc[NFSPROC_LOOKUP];
nfs->access = rpc[NFSPROC_ACCESS];
nfs->readlink = rpc[NFSPROC_READLINK];
nfs->read = rpc[NFSPROC_READ];
nfs->write = rpc[NFSPROC_WRITE];
nfs->create = rpc[NFSPROC_CREATE];
nfs->mkdir = rpc[NFSPROC_MKDIR];
nfs->symlink = rpc[NFSPROC_SYMLINK];
nfs->mknod = rpc[NFSPROC_MKNOD];
nfs->remove = rpc[NFSPROC_REMOVE];
nfs->rmdir = rpc[NFSPROC_RMDIR];
nfs->rename = rpc[NFSPROC_RENAME];
nfs->link = rpc[NFSPROC_LINK];
nfs->readdir = rpc[NFSPROC_READDIR];
nfs->readdirplus = rpc[NFSPROC_READDIRPLUS];
nfs->fsstat = rpc[NFSPROC_FSSTAT];
nfs->fsinfo = rpc[NFSPROC_FSINFO];
nfs->pathconf = rpc[NFSPROC_PATHCONF];
nfs->commit = rpc[NFSPROC_COMMIT];
}
#endif
int sigar_nfs_client_v2_get(sigar_t *sigar,
sigar_nfs_client_v2_t *nfs)
{
return SIGAR_ENOTIMPL;
}
int sigar_nfs_server_v2_get(sigar_t *sigar,
sigar_nfs_server_v2_t *nfs)
{
return SIGAR_ENOTIMPL;
}
int sigar_nfs_client_v3_get(sigar_t *sigar,
sigar_nfs_client_v3_t *nfs)
{
#if TARGET_OS_IPHONE
return SIGAR_ENOTIMPL;
#else
int status;
struct nfsstats stats;
if ((status = get_nfsstats(&stats)) != SIGAR_OK) {
return status;
}
map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.rpccnt[0]);
return SIGAR_OK;
#endif
}
int sigar_nfs_server_v3_get(sigar_t *sigar,
sigar_nfs_server_v3_t *nfs)
{
#if TARGET_OS_IPHONE
return SIGAR_ENOTIMPL;
#else
int status;
struct nfsstats stats;
if ((status = get_nfsstats(&stats)) != SIGAR_OK) {
return status;
}
map_nfs_stats((sigar_nfs_v3_t *)nfs, &stats.srvrpccnt[0]);
return SIGAR_OK;
#endif
}
#if !TARGET_OS_IPHONE
static char *get_hw_type(int type)
{
switch (type) {
case IFT_ETHER:
return "ether";
case IFT_ISO88025:
return "tr";
case IFT_FDDI:
return "fddi";
case IFT_ATM:
return "atm";
case IFT_L2VLAN:
return "vlan";
case IFT_IEEE1394:
return "firewire";
#ifdef IFT_BRIDGE
case IFT_BRIDGE:
return "bridge";
#endif
default:
return "unknown";
}
}
#endif
int sigar_arp_list_get(sigar_t *sigar,
sigar_arp_list_t *arplist)
{
#if TARGET_OS_IPHONE
return SIGAR_ENOTIMPL;
#else
size_t needed;
char *lim, *buf, *next;
struct rt_msghdr *rtm;
struct sockaddr_inarp *sin;
struct sockaddr_dl *sdl;
int mib[] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_LLINFO };
if (sysctl(mib, NMIB(mib), NULL, &needed, NULL, 0) < 0) {
return errno;
}
if (needed == 0) { /* empty cache */
return 0;
}
buf = malloc(needed);
if (sysctl(mib, NMIB(mib), buf, &needed, NULL, 0) < 0) {
free(buf);
return errno;
}
sigar_arp_list_create(arplist);
lim = buf + needed;
for (next = buf; next < lim; next += rtm->rtm_msglen) {
sigar_arp_t *arp;
SIGAR_ARP_LIST_GROW(arplist);
arp = &arplist->data[arplist->number++];
rtm = (struct rt_msghdr *)next;
sin = (struct sockaddr_inarp *)(rtm + 1);
sdl = (struct sockaddr_dl *)((char *)sin + SA_SIZE(sin));
sigar_net_address_set(arp->address, sin->sin_addr.s_addr);
sigar_net_address_mac_set(arp->hwaddr, LLADDR(sdl), sdl->sdl_alen);
if_indextoname(sdl->sdl_index, arp->ifname);
arp->flags = rtm->rtm_flags;
SIGAR_SSTRCPY(arp->type, get_hw_type(sdl->sdl_type));
}
free(buf);
return SIGAR_OK;
#endif
}
#if defined(DARWIN_HAS_LIBPROC_H)
int sigar_proc_port_get(sigar_t *sigar, int protocol,
unsigned long port, sigar_pid_t *pid)
{
sigar_proc_list_t pids;
int i, status, found=0;
if (!sigar->libproc) {
return SIGAR_ENOTIMPL;
}
status = sigar_proc_list_get(sigar, &pids);
if (status != SIGAR_OK) {
return status;
}
for (i=0; i<pids.number; i++) {
int n, num=0;
struct proc_fdinfo *fdinfo;
status = proc_fdinfo_get(sigar, pids.data[i], &num);
if (status != SIGAR_OK) {
continue;
}
fdinfo = (struct proc_fdinfo *)sigar->ifconf_buf;
for (n=0; n<num; n++) {
struct proc_fdinfo *fdp = &fdinfo[n];
struct socket_fdinfo si;
int rsize, family;
unsigned long lport;
if (fdp->proc_fdtype != PROX_FDTYPE_SOCKET) {
continue;
}
rsize = sigar->proc_pidfdinfo(pids.data[i], fdp->proc_fd,
PROC_PIDFDSOCKETINFO, &si, sizeof(si));
if (rsize != sizeof(si)) {
continue;
}
if (si.psi.soi_kind != SOCKINFO_TCP) {
continue;
}
if (si.psi.soi_proto.pri_tcp.tcpsi_state != TSI_S_LISTEN) {
continue;
}
family = si.psi.soi_family;
if (!((family == AF_INET) || (family == AF_INET6))) {
continue;
}
lport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport);
if (lport == port) {
*pid = pids.data[i];
found = 1;
break;
}
}
}
sigar_proc_list_destroy(sigar, &pids);
return found ? SIGAR_OK : ENOENT;
}
#endif
int sigar_os_sys_info_get(sigar_t *sigar,
sigar_sys_info_t *sysinfo)
{
#if TARGET_OS_IPHONE
char osversion[32] = "Unknown";
size_t s = sizeof(osversion);
sysctlbyname("kern.osversion", &osversion, &s, NULL, 0);
SIGAR_SSTRCPY(sysinfo->version, osversion);
struct utsname uname_data;
uname(&uname_data);
SIGAR_SSTRCPY(sysinfo->name, "iOS");
SIGAR_SSTRCPY(sysinfo->vendor_name, "Apple");
SIGAR_SSTRCPY(sysinfo->vendor, "Apple");
SIGAR_SSTRCPY(sysinfo->vendor_version, uname_data.release);
SIGAR_SSTRCPY(sysinfo->vendor_code_name, uname_data.machine);
SIGAR_SSTRCPY(sysinfo->description, uname_data.machine);
#else
char *codename = NULL;
int version_major, version_minor, version_fix;
SIGAR_SSTRCPY(sysinfo->name, "macOS");
SIGAR_SSTRCPY(sysinfo->vendor_name, "macOS");
SIGAR_SSTRCPY(sysinfo->vendor, "Apple");
FILE *fp = popen("/usr/bin/sw_vers -productVersion", "r");
if (fp == NULL) {
return SIGAR_ENOTIMPL;
}
char str[1024];
int count;
char *val = fgets(str, sizeof(str) - 1, fp);
pclose(fp);
count = sscanf(val, "%d.%d.%d", &version_major, &version_minor, &version_fix);
if(count < 2) {
return SIGAR_ENOTIMPL;
}
snprintf(sysinfo->vendor_version,
sizeof(sysinfo->vendor_version),
"%d.%d",
version_major, version_minor);
snprintf(sysinfo->version,
sizeof(sysinfo->version),
"%s.%d",
sysinfo->vendor_version, version_fix);
if (version_major == 10) {
switch (version_minor) {
case 2:
codename = "Jaguar";
break;
case 3:
codename = "Panther";
break;
case 4:
codename = "Tiger";
break;
case 5:
codename = "Leopard";
break;
case 6:
codename = "Snow Leopard";
break;
case 7:
codename = "Lion";
break;
case 8:
codename = "Mountain Lion";
break;
case 9:
codename = "Mavericks";
break;
case 10:
codename = "Yosemite";
break;
case 11:
codename = "El Capitan";
break;
case 12:
codename = "Sierra";
break;
case 13:
codename = "High Sierra";
break;
case 14:
codename = "Mojave";
break;
case 15:
codename = "Catalina";
break;
default:
codename = "Unknown";
break;
}
}
else {
return SIGAR_ENOTIMPL;
}
SIGAR_SSTRCPY(sysinfo->vendor_code_name, codename);
snprintf(sysinfo->description,
sizeof(sysinfo->description),
"%s %s",
sysinfo->vendor_name, sysinfo->vendor_code_name);
#endif
const char * arch = "unknown";
size_t size;
cpu_type_t type;
cpu_subtype_t subtype;
size = sizeof(type);
sysctlbyname("hw.cputype", &type, &size, NULL, 0);
size = sizeof(subtype);
sysctlbyname("hw.cpusubtype", &subtype, &size, NULL, 0);
if (type == CPU_TYPE_X86_64) {
arch = "x86_64";
} else if (type == CPU_TYPE_X86) {
arch = "x86";
} else if (type == CPU_TYPE_POWERPC) {
arch = "powerpc";
} else if (type == CPU_TYPE_POWERPC64) {
arch = "powerpc64";
} else if (type == CPU_TYPE_ARM) {
switch(subtype) {
#ifdef CPU_SUBTYPE_ARM_V6
case CPU_SUBTYPE_ARM_V6:
arch = "armv6";
break;
#endif
#ifdef CPU_SUBTYPE_ARM_V7
case CPU_SUBTYPE_ARM_V7:
arch = "armv7";
break;
#endif
#ifdef CPU_SUBTYPE_ARM_V7S
case CPU_SUBTYPE_ARM_V7S:
arch = "armv7s";
break;
#endif
#ifdef CPU_SUBTYPE_ARM_V8
case CPU_SUBTYPE_ARM_V8:
arch = "armv8";
break;
#endif
default:
arch = "arm";
}
#ifdef CPU_TYPE_ARM64
} else if (type == CPU_TYPE_ARM64) {
arch = "arm64";
#endif
}
SIGAR_SSTRCPY(sysinfo->arch, arch);
return SIGAR_OK;
}
int sigar_os_is_in_container(sigar_t *sigar)
{
return 0;
}
|
timwr/sigar | examples/diskinfo.c | /*
* Copyright (c) 2008 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <unistd.h>
#include <inttypes.h>
#include <assert.h>
#include <string.h>
#include "sigar.h"
int getNumShards(const char *dbpath) {
sigar_t *sigar;
sigar_file_system_list_t fslist;
if (sigar_open(&sigar) == SIGAR_OK &&
sigar_file_system_list_get(sigar, &fslist) == SIGAR_OK) {
sigar_file_system_usage_t fsu;
memset(&fsu, 0, sizeof(fsu));
sigar_file_system_t fsi;
int best_match = 0;
int i;
for (i = 0; i < fslist.number; i++) {
sigar_file_system_t fs = fslist.data[i];
if (strstr(dbpath, fs.dir_name)) {
size_t len = strlen(fs.dir_name);
if (len > best_match) {
best_match = len;
sigar_file_system_usage_t fsusage;
if (sigar_file_system_usage_get(sigar, fs.dir_name,
&fsusage) == SIGAR_OK) {
fsu = fsusage;
fsi = fs;
}
}
}
}
sigar_file_system_list_destroy(sigar, &fslist);
sigar_close(sigar);
printf("For dbpath %s best mount point is %s dev name is %s:\n",
dbpath, fsi.dir_name, fsi.dev_name);
printf("Write Time = %lu Read Time = %lu Service time = %f Queue = %f FS Use = %f%% \n",
(unsigned long)fsu.disk.wtime, (unsigned long)fsu.disk.rtime, fsu.disk.service_time,
fsu.disk.queue, (fsu.use_percent*100));
if (fsu.disk.wtime > fsu.disk.rtime + (fsu.disk.rtime >> 1)) {
printf("Likely disk type: SSD\n");
return 4;
} else {
printf("Likely disk type: Spindle Disk\n");
return 2;
}
}
return 4;
}
int main(int argc, char **argv) {
if (argv[1])
getNumShards(argv[1]);
else
printf("Usage: diskinfo <mount>\n");
return 0;
}
|
imGit/OpenMV | src/omv/boards/OPENMV4/omv_boardconfig.h | <filename>src/omv/boards/OPENMV4/omv_boardconfig.h
/*
* This file is part of the OpenMV project.
* Copyright (c) 2013/2014 <NAME> <<EMAIL>>
* This work is licensed under the MIT license, see the file LICENSE for details.
*
* Board configuration and pin definitions.
*
*/
#ifndef __OMV_BOARDCONFIG_H__
#define __OMV_BOARDCONFIG_H__
// Architecture info
#define OMV_ARCH_STR "OMV4 H7 1024" // 33 chars max
#define OMV_BOARD_TYPE "H7"
#define OMV_UNIQUE_ID_ADDR 0x1FF1E800
// Flash sectors for the bootloader.
// Flash FS sector, main FW sector, max sector.
#define OMV_FLASH_LAYOUT {1, 2, 15}
#define OMV_XCLK_MCO (0U)
#define OMV_XCLK_TIM (1U)
// Sensor external clock source.
#define OMV_XCLK_SOURCE (OMV_XCLK_TIM)
// Sensor external clock timer frequency.
#define OMV_XCLK_FREQUENCY (12000000)
// Sensor PLL register value.
#define OMV_OV7725_PLL_CONFIG (0x41) // x4
// Sensor Banding Filter Value
#define OMV_OV7725_BANDING (0x7F)
// Bootloader LED GPIO port/pin
#define OMV_BOOTLDR_LED_PIN (GPIO_PIN_1)
#define OMV_BOOTLDR_LED_PORT (GPIOC)
// RAW buffer size
#define OMV_RAW_BUF_SIZE (409600)
// Enable hardware JPEG
#define OMV_HARDWARE_JPEG (1)
// Enable MT9V034 and LEPTON sensors
#define OMV_ENABLE_MT9V034 (1)
#define OMV_ENABLE_LEPTON (1)
// If buffer size is bigger than this threshold, the quality is reduced.
// This is only used for JPEG images sent to the IDE not normal compression.
#define JPEG_QUALITY_THRESH (320*240*2)
// Low and high JPEG QS.
#define JPEG_QUALITY_LOW 50
#define JPEG_QUALITY_HIGH 90
// Linker script constants (see the linker script template stm32fxxx.ld.S).
// Note: fb_alloc is a stack-based, dynamically allocated memory on FB.
// The maximum available fb_alloc memory = FB_ALLOC_SIZE + FB_SIZE - (w*h*bpp).
#define OMV_FFS_MEMORY CCM // Flash filesystem cache memory
#define OMV_MAIN_MEMORY SRAM1 // data, bss, stack and heap
#define OMV_DMA_MEMORY AXI_SRAM // DMA buffers memory.
#define OMV_FB_MEMORY AXI_SRAM // Framebuffer, fb_alloc
#define OMV_JPEG_MEMORY SRAM3 // JPEG buffer memory.
#define OMV_VOSPI_MEMORY SRAM4 // VoSPI buffer memory.
#define OMV_FB_SIZE (400K) // FB memory: header + VGA/GS image
#define OMV_FB_ALLOC_SIZE (96K) // minimum fb alloc size
#define OMV_STACK_SIZE (7K)
#define OMV_HEAP_SIZE (240K)
#define OMV_LINE_BUF_SIZE (3K) // Image line buffer round(640 * 2BPP * 2 buffers).
#define OMV_MSC_BUF_SIZE (12K) // USB MSC bot data
#define OMV_VFS_BUF_SIZE (1K) // VFS sturct + FATFS file buffer (624 bytes)
#define OMV_JPEG_BUF_SIZE (32 * 1024) // IDE JPEG buffer (header + data).
#define OMV_BOOT_ORIGIN 0x08000000
#define OMV_BOOT_LENGTH 128K
#define OMV_TEXT_ORIGIN 0x08040000
#define OMV_TEXT_LENGTH 1792K
#define OMV_CCM_ORIGIN 0x20000000 // Note accessible by CPU and MDMA only.
#define OMV_CCM_LENGTH 128K
#define OMV_SRAM1_ORIGIN 0x30000000
#define OMV_SRAM1_LENGTH 256K
#define OMV_SRAM3_ORIGIN 0x30040000
#define OMV_SRAM3_LENGTH 32K
#define OMV_SRAM4_ORIGIN 0x38000000
#define OMV_SRAM4_LENGTH 64K
#define OMV_AXI_SRAM_ORIGIN 0x24000000
#define OMV_AXI_SRAM_LENGTH 512K
// Use the MPU to set an uncacheable memory region.
#define OMV_DMA_REGION_BASE (OMV_AXI_SRAM_ORIGIN+(496*1024))
#define OMV_DMA_REGION_SIZE MPU_REGION_SIZE_16KB
/* SCCB/I2C */
#define SCCB_I2C (I2C1)
#define SCCB_AF (GPIO_AF4_I2C1)
#define SCCB_CLK_ENABLE() __I2C1_CLK_ENABLE()
#define SCCB_CLK_DISABLE() __I2C1_CLK_DISABLE()
#define SCCB_PORT (GPIOB)
#define SCCB_SCL_PIN (GPIO_PIN_8)
#define SCCB_SDA_PIN (GPIO_PIN_9)
#define SCCB_TIMING (0x20D09DE7) // Frequency: 100KHz Rise Time: 100ns Fall Time: 20ns
/* DCMI */
#define DCMI_TIM (TIM1)
#define DCMI_TIM_PIN (GPIO_PIN_8)
#define DCMI_TIM_PORT (GPIOA)
#define DCMI_TIM_AF (GPIO_AF1_TIM1)
#define DCMI_TIM_CHANNEL (TIM_CHANNEL_1)
#define DCMI_TIM_CLK_ENABLE() __TIM1_CLK_ENABLE()
#define DCMI_TIM_CLK_DISABLE() __TIM1_CLK_DISABLE()
#define DCMI_TIM_PCLK_FREQ() HAL_RCC_GetPCLK2Freq()
#define DCMI_RESET_PIN (GPIO_PIN_10)
#define DCMI_RESET_PORT (GPIOA)
#define DCMI_PWDN_PIN (GPIO_PIN_7)
#define DCMI_PWDN_PORT (GPIOD)
#define DCMI_FSIN_PIN (GPIO_PIN_5)
#define DCMI_FSIN_PORT (GPIOB)
#define DCMI_D0_PIN (GPIO_PIN_6)
#define DCMI_D1_PIN (GPIO_PIN_7)
#define DCMI_D2_PIN (GPIO_PIN_0)
#define DCMI_D3_PIN (GPIO_PIN_1)
#define DCMI_D4_PIN (GPIO_PIN_4)
#define DCMI_D5_PIN (GPIO_PIN_6)
#define DCMI_D6_PIN (GPIO_PIN_5)
#define DCMI_D7_PIN (GPIO_PIN_6)
#define DCMI_D0_PORT (GPIOC)
#define DCMI_D1_PORT (GPIOC)
#define DCMI_D2_PORT (GPIOE)
#define DCMI_D3_PORT (GPIOE)
#define DCMI_D4_PORT (GPIOE)
#define DCMI_D5_PORT (GPIOB)
#define DCMI_D6_PORT (GPIOE)
#define DCMI_D7_PORT (GPIOE)
#define DCMI_HSYNC_PIN (GPIO_PIN_4)
#define DCMI_VSYNC_PIN (GPIO_PIN_7)
#define DCMI_PXCLK_PIN (GPIO_PIN_6)
#define DCMI_HSYNC_PORT (GPIOA)
#define DCMI_VSYNC_PORT (GPIOB)
#define DCMI_PXCLK_PORT (GPIOA)
#define DCMI_RESET_LOW() HAL_GPIO_WritePin(DCMI_RESET_PORT, DCMI_RESET_PIN, GPIO_PIN_RESET)
#define DCMI_RESET_HIGH() HAL_GPIO_WritePin(DCMI_RESET_PORT, DCMI_RESET_PIN, GPIO_PIN_SET)
#define DCMI_PWDN_LOW() HAL_GPIO_WritePin(DCMI_PWDN_PORT, DCMI_PWDN_PIN, GPIO_PIN_RESET)
#define DCMI_PWDN_HIGH() HAL_GPIO_WritePin(DCMI_PWDN_PORT, DCMI_PWDN_PIN, GPIO_PIN_SET)
#define DCMI_FSIN_LOW() HAL_GPIO_WritePin(DCMI_FSIN_PORT, DCMI_FSIN_PIN, GPIO_PIN_RESET)
#define DCMI_FSIN_HIGH() HAL_GPIO_WritePin(DCMI_FSIN_PORT, DCMI_FSIN_PIN, GPIO_PIN_SET)
#define DCMI_VSYNC_IRQN EXTI9_5_IRQn
#define DCMI_VSYNC_IRQ_LINE (7)
#define WINC_SPI (SPI2)
#define WINC_SPI_AF (GPIO_AF5_SPI2)
#define WINC_SPI_TIMEOUT (1000)
// SPI1/2/3 clock source is PLL2 (160MHz/4 == 40MHz).
#define WINC_SPI_PRESCALER (SPI_BAUDRATEPRESCALER_4)
#define WINC_SPI_CLK_ENABLE() __HAL_RCC_SPI2_CLK_ENABLE()
#define WINC_SPI_SCLK_PIN (GPIO_PIN_13)
#define WINC_SPI_MISO_PIN (GPIO_PIN_14)
#define WINC_SPI_MOSI_PIN (GPIO_PIN_15)
#define WINC_SPI_SCLK_PORT (GPIOB)
#define WINC_SPI_MISO_PORT (GPIOB)
#define WINC_SPI_MOSI_PORT (GPIOB)
#define WINC_EN_PIN (GPIO_PIN_5)
#define WINC_CS_PIN (GPIO_PIN_12)
#define WINC_RST_PIN (GPIO_PIN_12)
#define WINC_IRQ_PIN (pin_D13)
#define WINC_EN_PORT (GPIOA)
#define WINC_CS_PORT (GPIOB)
#define WINC_RST_PORT (GPIOD)
#define WINC_CS_LOW() HAL_GPIO_WritePin(WINC_CS_PORT, WINC_CS_PIN, GPIO_PIN_RESET)
#define WINC_CS_HIGH() HAL_GPIO_WritePin(WINC_CS_PORT, WINC_CS_PIN, GPIO_PIN_SET)
#define I2C_PORT GPIOB
#define I2C_SIOC_PIN GPIO_PIN_10
#define I2C_SIOD_PIN GPIO_PIN_11
#define I2C_SIOC_H() HAL_GPIO_WritePin(I2C_PORT, I2C_SIOC_PIN, GPIO_PIN_SET)
#define I2C_SIOC_L() HAL_GPIO_WritePin(I2C_PORT, I2C_SIOC_PIN, GPIO_PIN_RESET)
#define I2C_SIOD_H() HAL_GPIO_WritePin(I2C_PORT, I2C_SIOD_PIN, GPIO_PIN_SET)
#define I2C_SIOD_L() HAL_GPIO_WritePin(I2C_PORT, I2C_SIOD_PIN, GPIO_PIN_RESET)
#define I2C_SIOD_READ() HAL_GPIO_ReadPin(I2C_PORT, I2C_SIOD_PIN)
#define I2C_SIOD_WRITE(bit) HAL_GPIO_WritePin(I2C_PORT, I2C_SIOD_PIN, bit);
#define I2C_SPIN_DELAY 32
#define LEPTON_SPI (SPI3)
#define LEPTON_SPI_AF (GPIO_AF6_SPI3)
// SPI1/2/3 clock source is PLL2 (160MHz/8 == 20MHz).
#define LEPTON_SPI_PRESCALER (SPI_BAUDRATEPRESCALER_8)
#define LEPTON_SPI_IRQn (SPI3_IRQn)
#define LEPTON_SPI_IRQHandler (SPI3_IRQHandler)
#define LEPTON_SPI_DMA_IRQn (DMA1_Stream0_IRQn)
#define LEPTON_SPI_DMA_STREAM (DMA1_Stream0)
#define LEPTON_SPI_DMA_REQUEST (DMA_REQUEST_SPI3_RX)
#define LEPTON_SPI_DMA_IRQHandler (DMA1_Stream0_IRQHandler)
#define LEPTON_SPI_RESET() __HAL_RCC_SPI3_FORCE_RESET()
#define LEPTON_SPI_RELEASE() __HAL_RCC_SPI3_RELEASE_RESET()
#define LEPTON_SPI_CLK_ENABLE() __HAL_RCC_SPI3_CLK_ENABLE()
#define LEPTON_SPI_CLK_DISABLE() __HAL_RCC_SPI3_CLK_DISABLE()
#define LEPTON_SPI_SCLK_PIN (GPIO_PIN_3)
#define LEPTON_SPI_MISO_PIN (GPIO_PIN_4)
#define LEPTON_SPI_MOSI_PIN (GPIO_PIN_5)
#define LEPTON_SPI_SSEL_PIN (GPIO_PIN_15)
#define LEPTON_SPI_SCLK_PORT (GPIOB)
#define LEPTON_SPI_MISO_PORT (GPIOB)
#define LEPTON_SPI_MOSI_PORT (GPIOB)
#define LEPTON_SPI_SSEL_PORT (GPIOA)
#endif //__OMV_BOARDCONFIG_H__
|
imGit/OpenMV | src/omv/lepton.h | <filename>src/omv/lepton.h
/*
* This file is part of the OpenMV project.
* Copyright (c) 2013-2018 <NAME> <<EMAIL>>
* This work is licensed under the MIT license, see the file LICENSE for details.
*
* Lepton driver.
*
*/
#ifndef __LEPTON_H__
#define __LEPTON_H__
#include "sensor.h"
#define LEPTON_XCLK_FREQ 24000000
int lepton_init(sensor_t *sensor);
#endif // __LEPTON_H__
|
jonayerdi/base64 | src/base64_file.c | <filename>src/base64_file.c
/***********************************************************************************
zlib License
Copyright (c) 2017 <NAME>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
***********************************************************************************/
#include "base64_file.h"
int base64_encode_file(FILE *input, FILE *output)
{
char buffer_in[BASE64_ENCODE_BUFFER_SIZE];
char buffer_out[BASE64_ENCODED_SIZE(BASE64_ENCODE_BUFFER_SIZE)];
size_t read;
size_t encoded;
size_t written;
do
{
read = fread(buffer_in, 1, BASE64_ENCODE_BUFFER_SIZE, input);
if(read == BASE64_ENCODE_BUFFER_SIZE)
{
base64_encode_aligned(buffer_in, read, buffer_out);
encoded = BASE64_ENCODED_SIZE(BASE64_ENCODE_BUFFER_SIZE);
written = fwrite(buffer_out, encoded, 1, output);
if(!written && encoded)
return BASE64_ERROR_WRITING;
}
else
{
base64_encode(buffer_in, read, buffer_out);
encoded = BASE64_ENCODED_SIZE(read);
written = fwrite(buffer_out, encoded, 1, output);
if(!written && encoded)
return BASE64_ERROR_WRITING;
break;
}
} while(1);
if(!feof(input))
return BASE64_ERROR_READING;
return BASE64_OK;
}
int base64_decode_file(FILE *input, FILE *output, size_t *error_offset)
{
int error;
char buffer_in[BASE64_DECODE_BUFFER_SIZE];
char buffer_out[BASE64_DECODED_SIZE(BASE64_DECODE_BUFFER_SIZE)];
size_t iterations = 0;
size_t read;
size_t decoded;
size_t written;
do
{
read = fread(buffer_in, 1, BASE64_DECODE_BUFFER_SIZE, input);
error = base64_decode(buffer_in, read, buffer_out, &decoded, error_offset);
if(error)
{
if(error_offset != NULL)
{
*error_offset += iterations * BASE64_DECODE_BUFFER_SIZE;
}
return error;
}
written = fwrite(buffer_out, decoded, 1, output);
if(!written && decoded)
return BASE64_ERROR_WRITING;
iterations++;
} while(read == BASE64_DECODE_BUFFER_SIZE);
if(!feof(input))
return BASE64_ERROR_READING;
return BASE64_OK;
}
|
jonayerdi/base64 | src/base64_app.c | <filename>src/base64_app.c
/***********************************************************************************
zlib License
Copyright (c) 2017 <NAME>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
***********************************************************************************/
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include "base64.h"
#include "base64_file.h"
/* This is to fix newline conversion for stdin and stdout */
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif
#define BASE64_STDIO_FILE "."
#define BASE64_MODE_NULL 0
#define BASE64_MODE_ENCODE 1
#define BASE64_MODE_DECODE 2
#define BASE64_MODE_STDIN 4
#define BASE64_MODE_STDOUT 8
#define BASE64_ERROR_ARGS 1
#define BASE64_ERROR_OPEN_INPUT 2
#define BASE64_ERROR_OUTPUT_EXISTS 3
#define BASE64_ERROR_OPEN_OUTPUT 4
#define BASE64_ERROR_PARSE_ARG1 5
#define BASE64_CLOSE_STREAMS(ISTREAM, OSTREAM, MODE) \
{ \
if((!((MODE) & BASE64_MODE_STDIN) && ((ISTREAM) != NULL))) \
fclose(ISTREAM); \
if((!((MODE) & BASE64_MODE_STDOUT) && ((OSTREAM) != NULL))) \
fclose(OSTREAM); \
}
int main(int argc, char *argv[])
{
/* Declare variables */
int retval;
size_t error_offset;
FILE *input = NULL;
FILE *output = NULL;
char mode = BASE64_MODE_NULL;
/* Check args count */
if(argc != 4)
{
printf("Usage:\n");
printf("base64 e|encode|d|decode <file_in> <file_out>\n");
printf("If <file_in> is set to " BASE64_STDIO_FILE " the program reads from stdin\n");
printf("If <file_out> is set to " BASE64_STDIO_FILE " the program writes to stdout\n");
return BASE64_ERROR_ARGS;
}
/* Parse args and run program */
else
{
/* Parse arg 1 -> BASE64_MODE_ENCODE or BASE64_MODE_DECODE */
if(!strcmp(argv[1], "e") || !strcmp(argv[1], "encode"))
mode = BASE64_MODE_ENCODE;
else if(!strcmp(argv[1], "d") || !strcmp(argv[1], "decode"))
mode = BASE64_MODE_DECODE;
else
{
fprintf(stderr, "Error: first argument must be one of these:\ne\nencode\nd\ndecode\n");
return BASE64_ERROR_PARSE_ARG1;
}
/* Parse arg 2 -> Input stream */
if(!strcmp(argv[2], BASE64_STDIO_FILE))
{
/* This is to fix newline conversion for stdin and stdout */
#ifdef _WIN32
_setmode(_fileno(stdin), O_BINARY);
#endif
input = stdin;
mode |= BASE64_MODE_STDIN;
}
else
{
input = fopen(argv[2], "rb");
if(input == NULL)
{
fprintf(stderr, "Error opening input file %s\n", argv[2]);
return BASE64_ERROR_OPEN_INPUT;
}
}
/* Parse arg 3 -> Output stream */
if(!strcmp(argv[3], BASE64_STDIO_FILE))
{
/* This is to fix newline conversion for stdin and stdout */
#ifdef _WIN32
_setmode(_fileno(stdout), O_BINARY);
#endif
output = stdout;
mode |= BASE64_MODE_STDOUT;
}
else
{
output = fopen(argv[3], "rb");
if(output != NULL)
{
BASE64_CLOSE_STREAMS(input, output, mode);
fprintf(stderr, "Error: output file %s already exists\n", argv[3]);
return BASE64_ERROR_OUTPUT_EXISTS;
}
output = fopen(argv[3], "wb");
if(output == NULL)
{
BASE64_CLOSE_STREAMS(input, output, mode);
fprintf(stderr, "Error opening output file %s\n", argv[3]);
return BASE64_ERROR_OPEN_OUTPUT;
}
}
/* Encode or decode input stream into output stream */
if(mode & BASE64_MODE_ENCODE)
retval = base64_encode_file(input, output);
else
retval = base64_decode_file(input, output, &error_offset);
/* Print errors if necessary */
switch(retval)
{
case BASE64_OK:
/* OK */
break;
case BASE64_ERROR_READING:
fprintf(stderr, "Error reading from input file\n");
break;
case BASE64_ERROR_WRITING:
fprintf(stderr, "Error writing to output file\n");
break;
case BASE64_ERROR_DECODE_INVALID_BYTE:
fprintf(stderr, "Error decoding: Invalid input character at offset %u\n", (unsigned)error_offset);
break;
case BASE64_ERROR_DECODE_INVALID_SIZE:
fprintf(stderr, "Error decoding: Invalid input length\n");
break;
default:
fprintf(stderr, "Unknown error code: %d\n", retval);
break;
}
/* Close streams and return */
BASE64_CLOSE_STREAMS(input, output, mode);
return retval;
}
}
|
jonayerdi/base64 | src/base64.h | <filename>src/base64.h
/***********************************************************************************
zlib License
Copyright (c) 2017 <NAME>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
***********************************************************************************/
#ifndef _BASE64_H
#define _BASE64_H
#include <stddef.h> /* size_t, NULL */
#define BASE64_ENCODED_SIZE(DECODED_SIZE) ((((DECODED_SIZE) + 2) / 3) * 4)
#define BASE64_DECODED_SIZE(ENCODED_SIZE) (((ENCODED_SIZE) / 4) * 3)
#define BASE64_OK 0
#define BASE64_ERROR_DECODE_INVALID_BYTE -1
#define BASE64_ERROR_DECODE_INVALID_SIZE -2
void base64_encode_aligned(const char * restrict input, size_t size, char * restrict output);
void base64_encode(const char * restrict input, size_t size, char * restrict output);
int base64_decode(const char * restrict input, size_t size, char * restrict output, size_t *output_size, size_t *error_offset);
#endif /* _BASE64_H */
|
jonayerdi/base64 | src/base64_file.h | /***********************************************************************************
zlib License
Copyright (c) 2017 <NAME>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
***********************************************************************************/
#ifndef _BASE64_FILE_H
#define _BASE64_FILE_H
#include "base64.h"
#include <stdio.h> /* FILE */
#define BASE64_ERROR_READING -3
#define BASE64_ERROR_WRITING -4
/* !! Must be a multiple of 3 !! */
#define BASE64_ENCODE_BUFFER_SIZE 3072
/* !! Must be a multiple of 4 !! */
#define BASE64_DECODE_BUFFER_SIZE 4096
int base64_encode_file(FILE *input, FILE *output);
int base64_decode_file(FILE *input, FILE *output, size_t *error_offset);
#endif /* _BASE64_FILE_H */
|
jonayerdi/base64 | src/base64.c | /***********************************************************************************
zlib License
Copyright (c) 2017 <NAME>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
***********************************************************************************/
#include "base64.h"
char const *const base64_encode_lookup
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#define NA (-1) /* Invalid base64 bytes */
#define PADDING (0) /* Padding character '=' */
int const base64_decode_lookup[]
= { NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 62, NA, NA, NA, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, NA, NA, NA, PADDING, NA, NA
, NA, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, NA, NA, NA, NA, NA
, NA, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, NA, NA, NA, NA, NA
, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA };
#define BASE64_PADDING_CHAR ('=')
#define BASE64_ENCODE_3(BUFF_IN, BUFF_OUT) \
{ \
(BUFF_OUT)[0] = base64_encode_lookup[(unsigned char)(((BUFF_IN)[0] & 0xFC)>>2)]; \
(BUFF_OUT)[1] = base64_encode_lookup[(unsigned char)((((BUFF_IN)[0] & 0x03)<<4) | (((BUFF_IN)[1] & 0xF0)>>4))]; \
(BUFF_OUT)[2] = base64_encode_lookup[(unsigned char)((((BUFF_IN)[1] & 0x0F)<<2) | (((BUFF_IN)[2] & 0xC0)>>6))]; \
(BUFF_OUT)[3] = base64_encode_lookup[(unsigned char)(((BUFF_IN)[2] & 0x3F)>>0)]; \
}
#define BASE64_ENCODE_2(BUFF_IN, BUFF_OUT) \
{ \
(BUFF_OUT)[0] = base64_encode_lookup[(unsigned char)(((BUFF_IN)[0] & 0xFC)>>2)]; \
(BUFF_OUT)[1] = base64_encode_lookup[(unsigned char)((((BUFF_IN)[0] & 0x03)<<4) | (((BUFF_IN)[1] & 0xF0)>>4))]; \
(BUFF_OUT)[2] = base64_encode_lookup[(unsigned char)(((BUFF_IN)[1] & 0x0F)<<2)]; \
(BUFF_OUT)[3] = BASE64_PADDING_CHAR; \
}
#define BASE64_ENCODE_1(BUFF_IN, BUFF_OUT) \
{ \
(BUFF_OUT)[0] = base64_encode_lookup[(unsigned char)(((BUFF_IN)[0] & 0xFC)>>2)]; \
(BUFF_OUT)[1] = base64_encode_lookup[(unsigned char)(((BUFF_IN)[0] & 0x03)<<4)]; \
(BUFF_OUT)[2] = BASE64_PADDING_CHAR; \
(BUFF_OUT)[3] = BASE64_PADDING_CHAR; \
}
#define BASE64_DECODE(BUFF_IN, BUFF_OUT) \
{ \
(BUFF_OUT)[0] = (((unsigned char)base64_decode_lookup[(unsigned char)(BUFF_IN)[0]]) << 2) | (((unsigned char)base64_decode_lookup[(unsigned char)(BUFF_IN)[1]]) >> 4); \
(BUFF_OUT)[1] = (((unsigned char)base64_decode_lookup[(unsigned char)(BUFF_IN)[1]]) << 4) | (((unsigned char)base64_decode_lookup[(unsigned char)(BUFF_IN)[2]]) >> 2); \
(BUFF_OUT)[2] = (((unsigned char)base64_decode_lookup[(unsigned char)(BUFF_IN)[2]]) << 6) | (((unsigned char)base64_decode_lookup[(unsigned char)(BUFF_IN)[3]]) >> 0); \
}
#define BASE64_IS_VALID_BYTE(BYTE) (base64_decode_lookup[(unsigned char)(BYTE)] != NA && (((char)(BYTE)) != BASE64_PADDING_CHAR))
void base64_encode_aligned(const char * restrict input, size_t size, char * restrict output)
{
size_t i;
for(i = 0 ; i < (size / 3) ; i++)
{
BASE64_ENCODE_3(input, output);
input += 3, output += 4;
}
}
void base64_encode(const char * restrict input, size_t size, char * restrict output)
{
size_t i;
for(i = 0 ; i < (size / 3) ; i++)
{
BASE64_ENCODE_3(input, output);
input += 3, output += 4;
}
if((size % 3) == 2)
{
BASE64_ENCODE_2(input, output);
}
else if((size % 3) == 1)
{
BASE64_ENCODE_1(input, output);
}
}
int base64_decode(const char * restrict input, size_t size, char * restrict output, size_t *output_size, size_t *error_offset)
{
if(size == 0)
{
*output_size = 0;
}
else
{
*output_size = BASE64_DECODED_SIZE(size);
size_t iterations = (size / 4) - 1;
if((size % 4) != 0)
{
return BASE64_ERROR_DECODE_INVALID_SIZE;
}
/* Decode 4 byte blocks */
for(size_t i = 0 ; i < iterations ; i++)
{
for(size_t j = 0 ; j < 4 ; j++)
{
/* Check for invalid base64 input */
if(!BASE64_IS_VALID_BYTE(input[j]))
{
if(error_offset != NULL)
{
*error_offset = 4*i + j;
}
return BASE64_ERROR_DECODE_INVALID_BYTE;
}
}
BASE64_DECODE(input, output);
input += 4, output += 3;
}
/* Decode last 4 bytes */
for(size_t j = 0 ; j < 4 ; j++)
{
/* Check for invalid base64 input */
if(!BASE64_IS_VALID_BYTE(input[j]))
{
if(j > 1 && input[j] == BASE64_PADDING_CHAR)
{
--(*output_size);
}
else
{
if(error_offset != NULL)
{
*error_offset = 4*iterations + j;
}
return BASE64_ERROR_DECODE_INVALID_BYTE;
}
}
}
/* Check for padding char followed by non-padding char (invalid) */
if(input[2] == BASE64_PADDING_CHAR && input[3] != BASE64_PADDING_CHAR)
{
if(error_offset != NULL)
{
*error_offset = 4*iterations + 3;
}
return BASE64_ERROR_DECODE_INVALID_BYTE;
}
BASE64_DECODE(input, output);
}
return BASE64_OK;
}
|
hortont424/notebook | Notebook/NBUI/NBNotebookView.h | /*
* Copyright 2011 <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TIM HORTON "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL TIM HORTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Cocoa/Cocoa.h>
#import <NBCore/NBCore.h>
#import "NBCellViewDelegate.h"
@class NBCellView;
@interface NBNotebookView : NSView<NBCellViewDelegate,NBNotebookDelegate>
{
IBOutlet NBNotebook * notebook;
NSMapTable * cellViews;
NSMutableArray * selectedCellViews;
NSMutableArray * addCellTrackingAreas;
NBCellView * appendingCellView;
}
@property (nonatomic,assign) IBOutlet NBNotebook * notebook;
@property (nonatomic,readonly) NSMutableArray * selectedCellViews;
@property (nonatomic,readonly) NSMapTable * cellViews;
- (void)relayoutViews;
- (float)yForView:(NBCellView *)cellView;
- (id)undoManager;
- (void)setNotebook:(NBNotebook *)inNotebook;
- (void)cellAdded:(NBCell *)cell atIndex:(NSUInteger)index;
- (void)cellRemoved:(NBCell *)cell;
- (void)mouseDown:(NSEvent *)theEvent;
- (void)mouseEntered:(NSEvent *)theEvent;
- (void)mouseExited:(NSEvent *)theEvent;
- (void)cellViewResized:(NBCellView *)cellView;
- (void)cellViewTookFocus:(NBCellView *)cellView;
- (void)selectAll;
- (void)deselectAll;
- (void)selectedCell:(NBCellView *)cellView;
- (void)deselectedCell:(NBCellView *)cellView;
@end
|
hortont424/notebook | Notebook/NBUI/NBTextView.h | /*
* Copyright 2011 <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TIM HORTON "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL TIM HORTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Cocoa/Cocoa.h>
#import <NBCore/NBCore.h>
#import <RegexKit/RegexKit.h>
#import <Carbon/Carbon.h>
#import "NBCellSubview.h"
@class NBCellView;
@interface NBTextView : NSTextView<NSTextStorageDelegate,NBCellSubview>
{
NBCellView * parentCellView;
NSString * indentString;
RKRegex * leadingSpacesRegex;
}
@property (nonatomic,assign) NBCellView * parentCellView;
@property (readonly) NSString * indentString;
- (void)increaseIndent;
- (void)decreaseIndent;
@end
|
hortont424/notebook | Notebook/NBCore/NBCell.h | /*
* Copyright 2011 <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TIM HORTON "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL TIM HORTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Cocoa/Cocoa.h>
#define NBCellFinishedEvaluationNotification @"NBCellFinishedEvaluationNotification"
typedef enum
{
NBCellNone,
NBCellSnippet,
NBCellComment
} NBCellType;
typedef enum
{
NBCellChangedState = 0,
NBCellBusyState,
NBCellFailureState,
NBCellSuccessState
} NBCellState;
@class NBNotebook;
@class NBException;
@interface NBCell : NSObject
{
NSString * content;
NSString * output;
NBNotebook * notebook;
NBException * exception;
NSTimer * undoTimer;
NBCellType type;
NBCellState state;
}
@property (nonatomic,assign) NSString * content;
@property (nonatomic,assign) NSString * output;
@property (nonatomic,assign) NBNotebook * notebook;
@property (nonatomic,assign) NBException * exception;
@property (nonatomic,assign) NBCellType type;
@property (nonatomic,assign) NBCellState state;
- (void)evaluate;
@end
|
hortont424/notebook | Notebook/NBSettings/NBTheme.h | /*
* Copyright 2011 <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TIM HORTON "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL TIM HORTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Cocoa/Cocoa.h>
@class NBHighlightSettings;
@interface NBTheme : NSObject
{
NSString * filename;
NSString * name;
NSString * author;
NSString * version;
NSColorList * colors;
NSDictionary * fonts;
NSDictionary * highlights;
NSDictionary * settings;
}
@property (nonatomic,readonly) NSString * filename;
@property (nonatomic,readonly) NSString * name;
@property (nonatomic,readonly) NSString * author;
@property (nonatomic,readonly) NSString * version;
@property (nonatomic,readonly) NSColorList * colors;
@property (nonatomic,readonly) NSDictionary * fonts;
@property (nonatomic,readonly) NSDictionary * highlights;
@property (nonatomic,readonly) NSDictionary * settings;
+ (id)themeWithFile:(NSString *)aFilename;
- (id)initWithFile:(NSString *)aFilename;
+ (NSString *)fileExtension;
- (NSColor *)colorWithKey:(NSString *)key;
- (NSFont *)fontWithKey:(NSString *)key;
- (NBHighlightSettings *)highlightWithKey:(NSString *)key;
- (NSObject *)settingWithKey:(NSString *)key;
@end
|
hortont424/notebook | Notebook/NBCore/NSString-ranges.h | // Copyright (c) 2010-2011, <NAME>. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
@interface NSString (ranges)
- (NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)charset
options:(NSStringCompareOptions)opts
range:(NSRange)range;
- (NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)characterSet
afterLocation:(NSUInteger)startLocation
substring:(NSString**)outString;
- (NSRange)rangeOfWhitespaceStringAtBeginningOfLineForRange:(NSRange)range
substring:(NSString**)outString;
- (NSRange)rangeOfWhitespaceStringAtBeginningOfLineForRange:(NSRange)range;
- (NSUInteger)lineStartForRange:(NSRange)diveInRange;
- (unichar*)copyOfCharactersInRange:(NSRange)range;
+ (void)kodEnumerateLinesOfCharacters:(const unichar*)characters
ofLength:(NSUInteger)characterCount
withBlock:(void(^)(NSRange lineRange))block;
- (BOOL)hasPrefix:(NSString*)prefix options:(NSStringCompareOptions)options;
@end
|
hortont424/notebook | Notebook/NBSettings/NBSettingsController.h | /*
* Copyright 2011 <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TIM HORTON "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL TIM HORTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Cocoa/Cocoa.h>
#define NBThemeChangedNotification @"NBThemeChangedNotification"
#define NBTabWidthChangedNotification @"NBTabWidthChangedNotification"
#define NBMatchIndentChangedNotification @"NBMatchIndentChangedNotification"
#define NBPairCharactersChangedNotification @"NBPairCharactersChangedNotification"
#define NBWrapLinesChangedNotification @"NBWrapLinesChangedNotification"
#define NBTabInsertTypeChangedNotification @"NBTabInsertTypeChangedNotification"
#define NBCreateUntitledModeChangedNotification @"NBCreateUntitledModeChangedNotification"
#define NBHighlightSyntaxChangedNotification @"NBHighlightSyntaxChangedNotification"
#define NBHighlightGlobalsChangedNotification @"NBHighlightGlobalsChangedNotification"
#define NBFontNameChangedNotification @"NBFontNameChangedNotification"
#define NBThemeNameKey @"theme"
#define NBTabWidthKey @"tabWidth"
#define NBMatchIndentKey @"formatMatchIndent"
#define NBPairCharactersKey @"formatPairCharacters"
#define NBWrapLinesKey @"layoutWrapLines"
#define NBTabInsertTypeKey @"tabType"
#define NBCreateUntitledModeKey @"createUntitledMode"
#define NBHighlightSyntaxKey @"highlightSyntax"
#define NBHighlightGlobalsKey @"highlightGlobals"
#define NBFontNameKey @"fontName"
#define NBThemeNameDefault @"Tango"
#define NBTabWidthDefault 4
#define NBMatchIndentDefault YES
#define NBPairCharactersDefault NO
#define NBWrapLinesDefault YES
#define NBTabInsertTypeDefault 1
#define NBCreateUntitledModeDefault 0
#define NBHighlightSyntaxDefault YES
#define NBHighlightGlobalsDefault YES
#define NBFontNameDefault @""
typedef enum
{
NBCreateUntitledNever = 0,
NBCreateUntitledOnLaunch = 1,
NBCreateUntitledOnLaunchAndReactivation = 2
} NBCreateUntitledModes;
@class NBHighlightSettings;
@class NBTheme;
@interface NBSettingsController : NSObject
{
NSMutableDictionary * themes;
}
@property (readonly) NSString * themeName;
@property (nonatomic,assign) NSMutableDictionary * themes;
+ (NBSettingsController *)sharedInstance;
- (void)loadThemes:(NSArray *)paths;
- (NSString *)themeName;
- (NSUInteger)tabWidth;
- (BOOL)shouldMatchIndent;
- (BOOL)shouldHighlightGlobals;
- (BOOL)shouldPairCharacters;
- (BOOL)shouldWrapLines;
- (char)tabCharacter;
- (NBCreateUntitledModes)createUntitledMode;
- (BOOL)shouldHighlightSyntax;
- (BOOL)shouldHighlightGlobals;
- (NSColor *)colorWithKey:(NSString *)key;
- (NSFont *)fontWithKey:(NSString *)key;
- (NBHighlightSettings *)highlightWithKey:(NSString *)key;
- (NSObject *)settingWithKey:(NSString *)key;
@end
|
hortont424/notebook | Notebook/NBUI/NBCellView.h | /*
* Copyright 2011 <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TIM HORTON "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL TIM HORTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Cocoa/Cocoa.h>
#import <NBCore/NBCore.h>
#import "NBCellViewDelegate.h"
@class NBSourceView;
@class NBOutputView;
typedef struct _NBMargin
{
float left, right, top, bottom;
} NBMargin;
@interface NBCellView : NSView<NSTextViewDelegate>
{
NBCell * cell;
NBMargin margin;
id<NBCellViewDelegate> delegate;
BOOL selected;
BOOL selectionHandleHighlight;
NSTrackingArea * selectionHandleTrackingArea;
}
@property (nonatomic,retain) NBCell * cell;
@property (nonatomic,retain) id<NBCellViewDelegate> delegate;
@property (nonatomic,assign) BOOL selected;
@property (nonatomic,assign) BOOL selectionHandleHighlight;
@property (nonatomic,readonly) BOOL isRichText;
- (float)requestedHeight;
- (void)viewDidResize:(id)sender; // TODO: notification
- (void)enableContentResizeNotifications;
- (void)disableContentResizeNotifications;
- (NSRange)editableCursorLocation;
- (void)clearSelection;
@end
// TODO: figure out how to keep these private while still allowing subclasses to find them?
@interface NBCellView ()
- (void)subviewDidResize:(NSNotification *)aNotification;
- (void)subviewBecameFirstResponder:(NSNotification *)aNotification;
@end
|
hortont424/notebook | Notebook/NBCore/NBEngine.h | /*
* Copyright 2011 <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TIM HORTON "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL TIM HORTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Cocoa/Cocoa.h>
@class NBEngineBackend;
@class NBException;
typedef void (^SnippetCompletionCallback)(NBException * exception, NSString * output);
@interface NBEngine : NSObject
{
NSTask * backendTask;
NBEngineBackend * backend;
NSMutableArray * taskQueue;
SnippetCompletionCallback lastCompletionCallback;
BOOL busy;
}
- (void)abort;
+ (Class)backendClass;
+ (Class)highlighterClass;
+ (Class)encoderClass;
+ (Class)documentClass;
+ (NSString *)uuid;
+ (NSString *)name;
+ (NSString *)version;
+ (NSImage *)icon;
- (void)executeSnippet:(NSString *)snippet onCompletion:(SnippetCompletionCallback)completion;
- (oneway void)snippetComplete:(NBException *)exception withOutput:(NSString *)outputString;
- (NSDictionary *)globals;
- (id)globalWithKey:(NSString *)key;
@end
|
hortont424/notebook | Notebook/NBApplication/NBApplication.h | /*
* Copyright 2011 <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TIM HORTON "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL TIM HORTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <NBApplication/NBDocument.h>
#import <NBApplication/NBDocumentController.h>
#import <NBApplication/NBWindowController.h>
|
hortont424/notebook | Notebook/NBApplication/NBDocument.h | <reponame>hortont424/notebook
/*
* Copyright 2011 <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TIM HORTON "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL TIM HORTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Cocoa/Cocoa.h>
#import <NBCore/NBCore.h>
#import <NBUI/NBUI.h>
#define NBDocumentGlobalDragType @"NBDocumentGlobalDragType"
@interface NBDocument : NSDocument<NSWindowDelegate, NSTableViewDataSource>
{
NBNotebookView * notebookView;
NSButton * languageButton;
NSSplitView * splitView;
BOOL initialized;
BOOL initializedFromFile;
NBNotebook * notebook;
NSSearchField * searchField;
NSTableView * searchResultsView;
NSTableView * globalsTableView;
NSDictionary * globalsCache;
NSDictionary * filteredGlobals;
NSMutableArray * watchedGlobals;
}
@property (nonatomic,assign) IBOutlet NBNotebookView * notebookView;
@property (nonatomic,assign) IBOutlet NSButton * languageButton;
@property (nonatomic,assign) IBOutlet NSSplitView * splitView;
@property (nonatomic,assign) BOOL initialized;
@property (nonatomic,assign) BOOL initializedFromFile;
@property (nonatomic,assign) NBNotebook * notebook;
@property (nonatomic,readonly) BOOL hasKeyCell;
@property (nonatomic,readonly) BOOL hasSelectedCell;
@property (nonatomic,readonly) BOOL keyCellIsRichText;
@property (nonatomic,assign) IBOutlet NSSearchField * searchField;
@property (nonatomic,assign) IBOutlet NSTableView * searchResultsView;
@property (nonatomic,assign) IBOutlet NSTableView * globalsTableView;
- (void)initDocumentWithEngineClass:(Class)engineClass withTemplate:(NSString *)template;
+ (NSString *)fileExtension;
+ (NSString *)fileTypeName;
- (IBAction)doSomethingButton:(id)sender;
- (NBCellView *)keyCellView;
- (NSArray *)selectedCellViews;
- (IBAction)increaseIndent:(id)sender;
- (IBAction)decreaseIndent:(id)sender;
- (IBAction)insertCell:(id)sender;
- (IBAction)deleteCell:(id)sender;
- (IBAction)splitCell:(id)sender;
- (IBAction)mergeCells:(id)sender;
- (IBAction)evaluateCells:(id)sender;
- (IBAction)abortEvaluation:(id)sender;
- (IBAction)selectAllCells:(id)sender;
- (IBAction)selectAllCellsAboveCurrent:(id)sender;
- (IBAction)selectAllCellsBelowCurrent:(id)sender;
- (IBAction)searchGlobals:(id)sender;
@end
|
hortont424/notebook | Notebook/NBUI/NBUI.h | <reponame>hortont424/notebook<filename>Notebook/NBUI/NBUI.h
/*
* Copyright 2011 <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TIM HORTON "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL TIM HORTON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <NBUI/NBCellSubview.h>
#import <NBUI/NBCellView.h>
#import <NBUI/NBCellViewDelegate.h>
#import <NBUI/NBCommentCellView.h>
#import <NBUI/NBSourceCellView.h>
#import <NBUI/NBCreateNotebookView.h>
#import <NBUI/NBCreateNotebookViewDelegate.h>
#import <NBUI/NBBackgroundView.h>
#import <NBUI/NBNotebookView.h>
#import <NBUI/NBCommentView.h>
#import <NBUI/NBOutputView.h>
#import <NBUI/NBSourceView.h>
#import <NBUI/NBTextView.h>
|
jeffreyjb/Planet-Hopper | Source/PlanetHopper/SaveGameData.h | <gh_stars>0
// Copyright <NAME> 2020
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/SaveGame.h"
#include "SaveGameData.generated.h"
/**
*
*/
UCLASS()
class PLANETHOPPER_API USaveGameData : public USaveGame
{
GENERATED_BODY()
public:
USaveGameData();
UPROPERTY(VisibleAnywhere, Category = "Basic")
FString SaveSlotName;
UPROPERTY(VisibleAnywhere, Category = "Basic")
uint32 UserIndex;
UPROPERTY(EditAnywhere, Category = "Basic")
int32 SavedHighScore;
};
|
jeffreyjb/Planet-Hopper | Source/PlanetHopper/Planet.h | <filename>Source/PlanetHopper/Planet.h<gh_stars>0
// Copyright <NAME> 2020
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Components/StaticMeshComponent.h"
#include "Components/BoxComponent.h"
#include "PlanetHopperGameMode.h"
#include "Planet.generated.h"
UCLASS()
class PLANETHOPPER_API APlanet : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
APlanet();
// Called every frame
virtual void Tick(float DeltaTime) override;
void UpdateScore();
// Properties
UPROPERTY(BlueprintReadWrite, EditDefaultsOnly, Category = "Components")
UStaticMeshComponent *PlanetRootObj = nullptr;
UPROPERTY(BlueprintReadWrite, EditDefaultsOnly, Category = "Components")
UStaticMeshComponent *PlanetBodyMesh = nullptr;
UPROPERTY(BlueprintReadWrite, EditDefaultsOnly, Category = "Components")
UStaticMeshComponent *JumpPlatform = nullptr;
UPROPERTY(EditDefaultsOnly, Category = "Components")
UBoxComponent *LandingZone = nullptr;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
private:
void GetGameModeReference();
// Properties
bool bHasScored = false;
APlanetHopperGameMode *PlanetGameMode = nullptr;
};
|
jeffreyjb/Planet-Hopper | Source/PlanetHopper/PlanetHopperGameMode.h | <filename>Source/PlanetHopper/PlanetHopperGameMode.h
// Copyright <NAME> 2020
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "SaveGameData.h"
#include "PlanetHopperGameMode.generated.h"
/**
*
*/
UCLASS()
class PLANETHOPPER_API APlanetHopperGameMode : public AGameModeBase
{
GENERATED_BODY()
public:
APlanetHopperGameMode();
UFUNCTION(BlueprintCallable, Category = "Scoring")
void SetHighScore(int32 ScoreToSet);
UFUNCTION(BlueprintCallable, Category = "Scoring")
int32 GetHighScore() const;
UFUNCTION(BlueprintCallable, Category = "Scoring")
void SetCurrentScore(int32 ScoreToSet);
UFUNCTION(BlueprintCallable, Category = "Scoring")
int32 GetCurrentScore() const;
private:
UPROPERTY(EditDefaultsOnly, Category = "Scoring")
int32 CurrentScore = 0;
UPROPERTY(VisibleAnywhere, Category = "Scoring")
int32 HighScore = 0;
bool bAlteringHighScore = false;
USaveGameData *SaveGameInst = nullptr;
USaveGameData *LoadGameInst = nullptr;
void LoadSavedHighScore();
};
|
huangzhiqiang2012/ZQCycleScrollView | Source/ZQCycleScrollView.h | //
// ZQCycleScrollView.h
// ZQCycleScrollView
//
// Created by Darren on 2019/5/21.
// Copyright © 2019 Darren. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for ZQCycleScrollView.
FOUNDATION_EXPORT double ZQCycleScrollViewVersionNumber;
//! Project version string for ZQCycleScrollView.
FOUNDATION_EXPORT const unsigned char ZQCycleScrollViewVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <ZQCycleScrollView/PublicHeader.h>
|
MatthewA4/SHADERed | Options.h | <reponame>MatthewA4/SHADERed
#pragma once
#define PIPELINE_ITEM_NAME_LENGTH 64
// #define SEMANTIC_LENGTH 32
#define VARIABLE_NAME_LENGTH 256
#define MAX_RENDER_TEXTURES 16
#define MODEL_GROUP_NAME_LENGTH 64
#define SDL_GLSL_VERSION "#version 330"
#define IMGUI_INI_FILE "data/workspace.dat"
#define IMGUI_ERROR_COLOR ImVec4(1.0f, 0.17f, 0.13f, 1.0f)
#define IMGUI_WARNING_COLOR ImVec4(1.0f, 0.8f, 0.0f, 1.0f)
#define IMGUI_MESSAGE_COLOR ImVec4(0.106f, 0.631f, 0.886f, 1.0f)
// TODO: maybe dont use MAX_PATH but rather custom define?
#ifdef MAX_PATH
#undef MAX_PATH
#endif
#ifdef _WIN32
#define MAX_PATH 260
#else
#define MAX_PATH 512
#endif |
basaltex/aze | include/utf.h | <gh_stars>0
/* Copyright (c) 2018, <EMAIL>
*
* Distributed under the Boost Software License, Version 1.0 (found in the
* LICENSE file in the root directory of this source tree)
*/
/* this file has been automatically generated on 2018-11-26 18:00:16 and should not be edited manually. */
#pragma once
#include <algorithm>
#include <algorithm>
#include <iterator>
#include <type_traits>
#include <cstring>
#include <tuple>
# define UTF_PLATFORM_LITTLE_ENDIAN utf::little_endian
# define UTF_PLATFORM_BIG_ENDIAN utf::big_endian
# ifdef _WIN32
# define UTF_PLATFORM_ENDIANESS UTF_PLATFORM_LITTLE_ENDIAN
# define UTF_PLATFORM_BSWAP32(U32) _byteswap_ulong(U32)
# define UTF_PLATFORM_BSWAP16(U16) _byteswap_ushort(U16)
# else
# if defined(__linux__)
# include <endian.h>
# elif defined(OS_MACOSX)
# include <machine/endian.h>
# endif
# if __BYTE_ORDER == __LITTLE_ENDIAN
# define UTF_PLATFORM_ENDIANESS UTF_PLATFORM_LITTLE_ENDIAN
# elif __BYTE_ORDER == __BIG_ENDIAN
# define UTF_PLATFORM_ENDIANESS UTF_PLATFORM_BIG_ENDIAN
# endif
# define UTF_PLATFORM_BSWAP32(U32) __builtin_bswap32(U32)
# define UTF_PLATFORM_BSWAP16(U16) __builtin_bswap16(U16)
# endif
namespace utf
{
using u8string = std::string;
using u16string = std::u16string;
using u32string = std::u32string;
template <bool value,typename T,typename Y>
using conditional_t = typename std::conditional<value,T,Y>::type;
template <typename iterator_category>
using is_input_tag = std::is_same< iterator_category, std::input_iterator_tag >;
template <typename iterator_category>
constexpr bool is_input_tag_v = is_input_tag<iterator_category>::value;
template <typename iterator_category>
using is_forward_tag = std::is_same< iterator_category, std::forward_iterator_tag>;
template <typename iterator_category>
constexpr bool is_forward_tag_v = is_forward_tag<iterator_category>::value;
template <typename iterator_category>
using is_bidirectional_tag = std::is_same< iterator_category, std::bidirectional_iterator_tag>;
template <typename iterator_category>
constexpr bool is_bidirectional_tag_v = is_bidirectional_tag<iterator_category>::value;
template <typename iterator_category>
using is_random_access_tag = std::is_same< iterator_category, std::random_access_iterator_tag>;
template <typename iterator_category>
constexpr bool is_random_access_tag_v = is_random_access_tag<iterator_category>::value;
template<typename...> struct any_of : std::false_type { };
template<typename T> struct any_of<T> : T {};
template<typename T, typename ... Ts>
struct any_of<T, Ts...> : std::conditional<bool(T::value), T, any_of<Ts...>>::type {};
template<typename... Ts>
constexpr bool any_of_v = any_of<Ts...>::value;
template <typename category, template <typename> class... Ts>
constexpr bool category_any_of = any_of_v< Ts<category>... >;
template <typename category, template <typename> class... Ts>
using enable_if_category = typename std::enable_if<category_any_of<category,Ts...>>::type;
template <typename category, template <typename> class... Ts>
using enable_if_category_b = typename std::enable_if<category_any_of<category, Ts...>, bool>::type;
template <typename...>
struct type_list {};
template <bool v>
using bool_c = std::integral_constant<bool, v>;
template <typename T>
struct type_c { using type = T; };
template <typename...>
using void_t = void;
template< template <typename...> class tmpl, typename inst>
struct is_instance_of_template : std::false_type {};
template<template <typename...> class tmpl, typename... Ts>
struct is_instance_of_template <tmpl, tmpl<Ts...>> : std::true_type {};
template< template <typename...> class tmpl, typename... Ts>
static constexpr bool is_instance_of_template_v = is_instance_of_template<tmpl, Ts...>::value;
template < typename impl, template <typename...> class tag_tmpl>
struct policy_default;
#define UTF_POLICY_DEFAULT(ITER,POLICYTYPE,VALUE) \
template <typename base_iterator,typename...Ts> struct policy_default<ITER<base_iterator,Ts...>,POLICYTYPE> { using type = VALUE; }
template < typename impl, template <typename...> class policy_tmpl, typename selected, typename policy_list>
struct select_policy_handler_impl;
template < typename impl, template <typename...> class policy_tmpl, typename... selected, typename... policies>
struct select_policy_handler_impl<impl, policy_tmpl, type_list<selected...>, type_list<policies...>>
{
static_assert(sizeof...(selected) < 2, "Multiple overlapping policies specified, single policy expected.");
template <typename... >
struct select_first_or_default { using type = typename policy_default<impl, policy_tmpl>::type; };
template <typename selected_, typename... rest>
struct select_first_or_default<selected_, rest...>
{ using type = typename selected_::type; };
using type =
typename policy_tmpl<void>::template handler<
impl,
typename select_first_or_default<selected...>::type
>;
};
template < typename impl, template <typename...> class policy_tmpl, typename... selected, typename policy, typename... policies>
struct select_policy_handler_impl<impl, policy_tmpl, type_list< selected...>, type_list<policy, policies...>> :
select_policy_handler_impl <
impl,
policy_tmpl,
std::conditional_t<
is_instance_of_template_v<policy_tmpl, policy>,
type_list<selected..., policy>,
type_list<selected...>
>, type_list<policies...> > {};
template < typename impl, template <typename...> class policy_tmpl, typename... policies>
using select_policy_handler_t = typename select_policy_handler_impl<impl, policy_tmpl, type_list<>, type_list<policies...>>::type;
template <template <typename...> class test, typename default_, typename... args>
struct select_argument_or_default
{
using type = default_;
};
template <template <typename...> class test, typename default_, typename arg, typename... args>
struct select_argument_or_default<test, default_, arg, args...> :
std::conditional_t<test<arg>::value,
utf::type_c<arg>,
select_argument_or_default<test, default_, args...>
> {};
template <template <typename...> class test,typename...Ts>
using select_argument_or_default_t = typename select_argument_or_default<test, Ts...>::type;
template <typename T, typename enable = void>
struct has_value_type : std::false_type {};
template <typename T>
struct has_value_type<T, void_t<typename T::value_type>>
: std::true_type {};
template <typename T, typename enable = void>
struct has_begin_end : std::false_type {};
template <typename T>
struct has_begin_end<T, void_t<decltype(std::declval<T>().begin()), decltype(std::declval<T>().end())>>
: std::true_type {};
template <uint32_t value_>
struct replace_with {
static constexpr uint32_t value = value_;
};
using replace_with_fffd = replace_with<0xfffd>;
struct throw_exception {};
struct little_endian {};
struct big_endian {};
using native_endian = UTF_PLATFORM_ENDIANESS;
namespace detail
{
template <typename impl, typename policy, typename enable = void>
struct onerror_handler;
template <typename impl, typename policy, typename enable = void>
struct to_handler;
template <typename impl, typename policy, typename enable = void>
struct from_handler;
}
template <typename T>
struct onerror
{
using type = T;
template <typename...Ts>
using handler = detail::onerror_handler<Ts...>;
};
template <typename T>
struct from
{
using type = T;
template <typename...Ts>
using handler = detail::from_handler<Ts...>;
};
template <typename T>
struct to
{
using type = T;
template <typename...Ts>
using handler = detail::to_handler<Ts...>;
};
constexpr uint32_t utf_not_a_char = 0x0000FFFE; // { 0x00, 0x00, 0xFF, 0xFE };
constexpr uint32_t utf_replacement_char = 0x0000FFFD; //{ 0x00,0x00,0xFF,0xFD };
template <
typename to_endianness,
typename from_endianness = native_endian,
typename std::enable_if< std::is_convertible<from_endianness, to_endianness>::value,bool>::type = true
>
uint32_t codepoint_as(uint32_t codepoint)
{
return codepoint;
}
template <
typename to_endianness,
typename from_endianness = native_endian,
typename std::enable_if< !std::is_convertible<from_endianness, to_endianness>::value, bool>::type = true
>
uint32_t codepoint_as(uint32_t codepoint)
{
return UTF_PLATFORM_BSWAP32(codepoint);
}
template <
typename to_endianness,
typename from_endianness = native_endian,
typename std::enable_if< std::is_convertible<from_endianness, to_endianness>::value, bool>::type = true
>
uint16_t codeunit_as(uint16_t codeunit)
{
return codeunit;
}
template <
typename to_endianness,
typename from_endianness = native_endian,
typename std::enable_if< !std::is_convertible<from_endianness, to_endianness>::value, bool>::type = true
>
uint32_t codeunit_as(uint16_t codeunit)
{
return UTF_PLATFORM_BSWAP16(codeunit);
}
constexpr uint8_t utf8_bom[] = { 0xEF,0xBB,0xBF };
constexpr uint8_t utf16_little_endian_bom[] = { 0xFF,0xFE };
constexpr uint8_t utf16_big_endian_bom[] = { 0xFE,0xFF };
constexpr uint8_t utf32_little_endian_bom[] = { 0xFF,0xFE,0x00,0x00 };
constexpr uint8_t utf32_big_endian_bom[] = { 0x00,0x00,0xFE,0xFF };
enum class bom_type
{
none,
utf8,
utf16_little_endian,
utf16_big_endian,
utf32_little_endian,
utf32_big_endian,
};
}
namespace utf
{
struct utf_iterator_access
{
template <typename impl_type>
static void increment(impl_type& impl)
{
impl.increment();
}
template <typename impl_type>
static void decrement(impl_type& impl)
{
impl.decrement();
}
template <typename impl_type>
static bool equal(const impl_type& impl, const impl_type& other)
{
return impl.equal(other);
}
template <typename impl_type>
static typename impl_type::reference dereference(const impl_type& impl)
{
return impl.dereference();
}
};
template <
typename impl,
typename base_iterator,
typename impl_category,
typename fn_category,
typename value_type_,
typename reference_type_,
typename enable=void
>
struct utf_iterator_base
{
using iterator_category = impl_category;
using value_type = value_type_;
using difference_type = std::ptrdiff_t;
using pointer = typename std::add_pointer<value_type_>::type;
using reference = reference_type_;
protected:
impl& derived()
{
return *static_cast<impl*>(this);
}
const impl& derived() const
{
return *static_cast<const impl*>(this);
}
public:
reference operator*() const
{
return utf_iterator_access::dereference(derived());
}
friend bool operator==(const impl& first,const impl& second)
{
return utf_iterator_access::equal(first,second);
}
friend bool operator!=(const impl& first, const impl& second)
{
return !utf_iterator_access::equal(first, second);
}
impl& operator++()
{
utf_iterator_access::increment(this->derived());
return this->derived();
}
template <typename iterator_type = impl>
impl operator++(int)
{
impl result(this->derived());
++(*this);
return result;
}
};
template <typename iterator_type>
struct resultof_postfix_increment : iterator_type
{
template<typename T, typename enable = void>
struct resultof_postfix_increment_impl
{ using type = iterator_type; };
template<typename T>
struct resultof_postfix_increment_impl<T, void_t<typename T::postfix_increment_result_type>>
{
using type = typename T::postfix_increment_result_type;
};
using type = typename resultof_postfix_increment_impl<resultof_postfix_increment>::type;
};
template <typename impl, typename base_iterator, typename impl_catagory,typename fn_category, typename value, typename reference>
struct utf_iterator_base < impl, base_iterator, impl_catagory, fn_category ,value, reference,
enable_if_category<fn_category, is_input_tag, is_forward_tag>
> : utf_iterator_base < impl, base_iterator, impl_catagory, void, value, reference >
{
impl& operator++()
{
utf_iterator_access::increment(this->derived());
return this->derived();
}
template <typename iterator_type=impl>
auto operator++(int)
{
typename resultof_postfix_increment<impl>::type result(this->derived());
++(*this);
return result;
}
};
template <typename impl, typename base_iterator, typename impl_catagory,typename fn_category, typename value, typename reference>
struct utf_iterator_base < impl, base_iterator, impl_catagory, fn_category, value, reference,
enable_if_category<fn_category, is_bidirectional_tag, is_random_access_tag>
> : utf_iterator_base<impl, base_iterator, impl_catagory, std::forward_iterator_tag, value, reference>
{
impl& operator--()
{
utf_iterator_access::decrement(this->derived());
return this->derived();
}
impl operator--(int)
{
impl result(this->derived());
--(*this);
return result;
}
};
template <typename impl, typename base_iterator, typename impl_category, typename value, typename reference>
struct utf_iterator : utf_iterator_base<impl,base_iterator,impl_category, impl_category,value,reference>{};
}
namespace utf
{
template <typename base_iterator, typename... policies>
class utf8_to_utf32_iterator;
UTF_POLICY_DEFAULT(utf8_to_utf32_iterator, onerror, throw_exception);
UTF_POLICY_DEFAULT(utf8_to_utf32_iterator, to, little_endian);
namespace detail {
template<uint32_t value, typename base_iterator,typename... Ts>
struct onerror_handler< utf8_to_utf32_iterator<base_iterator,Ts...>, replace_with<value>, void>
{
static uint32_t apply(const std::string& errmsg) {
return value;
}
};
template <typename base_iterator,typename... Ts>
struct onerror_handler< utf8_to_utf32_iterator<base_iterator,Ts...>, throw_exception, void>
{
static uint32_t apply(const std::string& errmsg) { throw std::runtime_error(errmsg); }
};
template<typename endianness, typename base_iterator,typename... Ts>
struct to_handler < utf8_to_utf32_iterator<base_iterator,Ts...>, endianness>
{
static uint32_t apply(uint32_t codepoint) {
return codepoint_as<endianness>(codepoint);
}
};
}
/*** common iterator implementation */
template <typename impl, typename base_iterator, typename impl_catagory, typename value_type, typename reference_type, typename... policies>
struct utf8_to_utf32_iterator_base :
utf_iterator< impl, base_iterator, impl_catagory, value_type, reference_type>
{
protected:
using base_type = typename utf8_to_utf32_iterator_base::utf_iterator;
friend utf_iterator_access;
using error_policy = select_policy_handler_t<impl, onerror, policies...>;
using to_policy = select_policy_handler_t<impl, to, policies...>;
utf8_to_utf32_iterator_base() {};
utf8_to_utf32_iterator_base(base_iterator pos, const base_iterator end) :
pos_(pos),
end_(end),
current_(0),
replace_(0),
size_(5)
{};
static inline size_t codepoint_bytes(uint8_t value)
{
if (value < 0x80)
return 1;
for (size_t i = 0; i < 5; ++i)
if (!(value & 0x80 >> i))
return i;
return 0;
}
template < typename onerror_policy, typename to_policy>
static uint32_t read_next_impl(base_iterator& pos, const base_iterator& end, onerror_policy, to_policy, int8_t& replace, int8_t& consumed)
{
uint8_t start_byte = *pos++; ++consumed;
if ((start_byte & 0xC0) == 0x80) {
return onerror_policy::apply("invalid start byte decoding utf8 string.");
}
size_t byte_count = codepoint_bytes(start_byte);
if (!byte_count)
return onerror_policy::apply("invalid byte count decoding utf8 string.");
uint32_t codepoint = start_byte;
for (size_t i = 1; i < byte_count; ++i, ++pos, ++consumed)
{
if (pos == end)
return (replace = static_cast<int8_t>(i-1),onerror_policy::apply("unexpected eof deocding of ut8 string."));
else if ((*pos & 0xC0) != 0x80)
return (replace = static_cast<int8_t>(i-1),onerror_policy::apply("invalid byte deocding of ut8 string. expected continuation byte."));
codepoint <<= 6;
codepoint |= static_cast<uint32_t>(*pos) & 0x3F;
}
static const uint32_t masks[] =
{
0x7Fu,
0x7FFu,
0xFFFFu,
0x1FFFFFu,
};
return codepoint & masks[byte_count - 1];
}
template < typename onerror_policy, typename to_policy>
static uint32_t read_next(base_iterator& pos, const base_iterator& end, onerror_policy, to_policy, int8_t& replace,int8_t& consumed)
{
consumed = 0;
replace = 0;
return to_policy::apply(read_next_impl(pos, end, onerror_policy(), to_policy(), replace, consumed));
}
template < typename onerror_policy, typename to_policy>
static uint32_t read_prev_impl(base_iterator& pos, const base_iterator& start, onerror_policy, to_policy, int8_t& replace, int8_t& consumed)
{
base_iterator prev(pos);
base_iterator end(pos);
size_t byte_count = 1;
for (--prev; byte_count < 5; ++byte_count, --prev)
{
if ((*prev & 0xC0) != 0x80)
{
if (codepoint_bytes(*prev) == byte_count)
break;
return (--pos, onerror_policy::apply("invalid byte count decoding utf8 string."));
}
if (prev == start)
return (--pos, onerror_policy::apply("unexpected sof deocding of ut8 string."));
}
pos = prev;
return read_next_impl(prev, end, onerror_policy(), to_policy(), replace, consumed);
}
template < typename onerror_policy, typename to_policy>
static uint32_t read_prev(base_iterator& pos, const base_iterator& end, onerror_policy, to_policy, int8_t& replace, int8_t& consumed)
{
consumed = 0;
replace = 0;
return to_policy::apply(read_prev_impl(pos, end, onerror_policy(), to_policy(), replace, consumed));
}
typename base_type::reference dereference() const
{
if (!replace_ && read_required())
{
base_iterator pos(pos_);
read(pos);
}
return this->current_;
}
bool equal(const impl& other) const
{
return pos_ == other.pos_;
}
void increment()
{
if (replace_ > 0)
return (void)--replace_;
if (read_required())
read(pos_);
else
std::advance(pos_, size_);
size_ = 5;
}
bool read_required() const
{
return size_ == 5;
}
void read(base_iterator& pos) const
{
current_ = read_next(
pos,
end_,
error_policy(), to_policy(),
replace_,
size_
);
}
mutable base_iterator pos_;
base_iterator end_;
mutable uint32_t current_;
mutable int8_t size_;
mutable int8_t replace_;
};
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf8_to_utf32_iterator_impl;
/*** input iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf8_to_utf32_iterator_impl<impl, base_iterator, base_category,
enable_if_category< base_category, is_input_tag >
, policies...> :
utf8_to_utf32_iterator_base<impl, base_iterator, std::input_iterator_tag, uint32_t, const uint32_t&, policies...>
{
protected:
using base_type = typename utf8_to_utf32_iterator_impl::utf8_to_utf32_iterator_base;
friend utf_iterator_access;
utf8_to_utf32_iterator_impl()
{}
utf8_to_utf32_iterator_impl(base_iterator pos, const base_iterator end) :
base_type(pos,end)
{
this->size_ = 0;
if (pos != end)
this->read(this->pos_);
}
void increment()
{
if (this->replace_ > 0)
return (void)--this->replace_;
if (this->pos_ != this->end_)
this->read(this->pos_);
else
this->size_ = 0;
}
bool equal(const impl& other) const
{
return other.pos_ == this->pos_ && other.size_ == this->size_ && this->replace_ == other.replace_;
}
typename base_type::reference dereference() const
{
return this->current_;
}
};
/*** forward iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf8_to_utf32_iterator_impl<impl, base_iterator, base_category,
enable_if_category< base_category, is_forward_tag>, policies...>
: utf8_to_utf32_iterator_base<impl, base_iterator, std::forward_iterator_tag, uint32_t, const uint32_t&, policies...>
{
protected:
using base_type = typename utf8_to_utf32_iterator_impl::utf8_to_utf32_iterator_base;
using base_type::base_type;
};
/*** bidirectional & random access iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf8_to_utf32_iterator_impl<impl, base_iterator, base_category,
enable_if_category<base_category, is_bidirectional_tag, is_random_access_tag>, policies...>
: utf8_to_utf32_iterator_base<impl, base_iterator, std::bidirectional_iterator_tag, uint32_t, const uint32_t&, policies...>
{
protected:
friend utf_iterator_access;
using base_type = typename utf8_to_utf32_iterator_impl::utf8_to_utf32_iterator_base;
using typename base_type::error_policy;
using typename base_type::to_policy;
utf8_to_utf32_iterator_impl()
{}
utf8_to_utf32_iterator_impl(base_iterator pos, base_iterator start, base_iterator end) :
base_type(pos,end),
start_(start)
{}
void decrement()
{
if (this->replace_ < 0)
return (void)++this->replace_;
this->derived().current_ = this->read_prev(
this->pos_,
this->start_,
error_policy(), to_policy(),
this->replace_,
this->size_
);
}
base_iterator start_;
};
template <typename base_iterator, typename... policies>
class utf8_to_utf32_iterator :
public utf8_to_utf32_iterator_impl<
utf8_to_utf32_iterator<base_iterator, policies...>,
base_iterator,
typename std::iterator_traits<base_iterator>::iterator_category,
void, policies...
>
{
using impl_type = typename utf8_to_utf32_iterator::utf8_to_utf32_iterator_impl;
friend typename impl_type::base_type;
public:
utf8_to_utf32_iterator() {};
template< typename category_type=typename std::iterator_traits<base_iterator>::iterator_category,
typename bidirectional_or_random_access=enable_if_category<category_type,is_bidirectional_tag,is_random_access_tag>>
utf8_to_utf32_iterator(base_iterator pos, base_iterator start, base_iterator end) : impl_type(pos, start, end) {}
template< typename category_type=typename std::iterator_traits<base_iterator>::iterator_category,
typename input_or_forward=enable_if_category<category_type, is_input_tag, is_forward_tag>>
utf8_to_utf32_iterator(base_iterator pos, base_iterator end) : impl_type(pos, end) {}
};
template <typename... policies,typename base_iterator,
typename category_type = typename std::iterator_traits<base_iterator>::iterator_category,
enable_if_category_b<category_type, is_bidirectional_tag, is_random_access_tag> = true>
auto make_utf8_to_utf32_iterator(base_iterator begin, base_iterator end)
{
return utf8_to_utf32_iterator<base_iterator, policies...>{begin, begin,end};
}
template <typename... policies, typename base_iterator,
typename category_type = typename std::iterator_traits<base_iterator>::iterator_category,
enable_if_category_b<category_type, is_input_tag, is_forward_tag> = true>
auto make_utf8_to_utf32_iterator(base_iterator begin, base_iterator end)
{
return utf8_to_utf32_iterator<base_iterator, policies...>{begin, end};
}
}
namespace utf
{
template <typename base_iterator, typename... policies>
class utf32_to_utf8_iterator;
UTF_POLICY_DEFAULT(utf32_to_utf8_iterator, onerror, throw_exception);
UTF_POLICY_DEFAULT(utf32_to_utf8_iterator, from, little_endian);
namespace detail {
template<uint32_t value,typename base_iterator, typename... Ts>
struct onerror_handler< utf32_to_utf8_iterator<base_iterator,Ts...>, replace_with<value>, void>
{
static uint32_t apply(const std::string& errmsg,uint32_t& codepoint) {
return codepoint = value;
}
};
template <typename base_iterator,typename... Ts>
struct onerror_handler< utf32_to_utf8_iterator<base_iterator,Ts...>, throw_exception, void>
{
static uint32_t apply(const std::string& errmsg, uint32_t& codepoint) {
throw std::runtime_error(errmsg);
}
};
template<typename endianness,typename base_iterator, typename... Ts>
struct from_handler < utf32_to_utf8_iterator<base_iterator,Ts...>, endianness>
{
static uint32_t apply(uint32_t codepoint) {
return codepoint_as<native_endian, endianness>(codepoint);
}
};
}
/*** common iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename value_type, typename reference_type, typename... policies>
struct utf32_to_utf8_iterator_base :
utf_iterator< impl, base_iterator, base_category, value_type, reference_type>
{
friend utf_iterator_access;
protected:
utf32_to_utf8_iterator_base() {};
utf32_to_utf8_iterator_base(base_iterator pos) :
current_{ 0 },
size_(0),
index_(4),
pos_(pos)
{}
using error_policy = select_policy_handler_t<impl, onerror, policies...>;
using from_policy = select_policy_handler_t<impl, from, policies...>;
template <typename onerror_policy, typename from_policy>
static size_t read_next(base_iterator& pos, uint8_t* bytes,onerror_policy, from_policy)
{
uint32_t codepoint = from_policy::apply(*pos++);
if (codepoint > 0x10FFFF)
onerror_policy::apply("error encoding utf8 string, invalid codepoint.", codepoint);
if (codepoint <= 0x007F)
{
bytes[0] = static_cast<uint8_t>(codepoint);
bytes[1] = 0;
bytes[2] = 0;
bytes[3] = 0;
return 1;
}
if (codepoint <= 0x07FF)
{
bytes[0] = static_cast<uint8_t>((codepoint >> 6 & 0x1F) | 0xC0);
bytes[1] = static_cast<uint8_t>((codepoint & 0x3F) | 0x80);
bytes[2] = 0;
bytes[3] = 0;
return 2;
}
if (codepoint <= 0xFFFF)
{
bytes[0] = static_cast<uint8_t>((codepoint >> 12 & 0x0F) | 0xE0);
bytes[1] = static_cast<uint8_t>((codepoint >> 6 & 0x3F) | 0x80);
bytes[2] = static_cast<uint8_t>((codepoint & 0x3F) | 0x80);
bytes[3] = 0;
return 3;
}
if (codepoint <= 0x10FFFF)
{
bytes[0] = static_cast<uint8_t>((codepoint >> 18 & 0x0E) | 0xF0);
bytes[1] = static_cast<uint8_t>((codepoint >> 12 & 0x3F) | 0x80);
bytes[2] = static_cast<uint8_t>((codepoint >> 6 & 0x3F) | 0x80);
bytes[3] = static_cast<uint8_t>((codepoint & 0x3F) | 0x80);
return 4;
}
return 0;
}
template < typename onerror_policy, typename from_policy>
static size_t read_prev(base_iterator& pos, uint8_t* bytes,onerror_policy, from_policy)
{
base_iterator prev(--pos);
return read_next(prev,bytes, onerror_policy(), from_policy());
}
using base_type = typename utf32_to_utf8_iterator_base::utf_iterator;
typename base_type::reference dereference() const
{
read_pending();
return this->current_[this->index_];
}
bool equal(const impl& other) const
{
return this->pos_ == other.pos_ && ((this->index_ | other.index_) & 3) == 0;
}
void increment()
{
read_pending();
++this->index_;
if (this->index_ == this->size_)
this->index_ = 4;
}
inline void read_pending() const
{
if (this->index_ == 4) {
this->size_ = read_next(this->pos_, this->current_, error_policy(), from_policy());
this->index_ = 0;
}
}
mutable uint8_t current_[4];
mutable size_t index_;
mutable size_t size_;
mutable base_iterator pos_;
};
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf32_to_utf8_iterator_impl;
/*** input iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf32_to_utf8_iterator_impl<impl, base_iterator, base_category,
enable_if_category< typename std::iterator_traits<base_iterator>::iterator_category, is_input_tag>
, policies...> :
utf32_to_utf8_iterator_base<impl, base_iterator, base_category, uint8_t, const uint8_t&, policies...>
{
protected:
struct postfix_increment_result_type {
postfix_increment_result_type(const impl& iter) :
value_(*iter)
{}
uint8_t operator*() const { return value_; }
private:
uint8_t value_;
};
friend utf_iterator_access;
using base_type = typename utf32_to_utf8_iterator_impl::utf32_to_utf8_iterator_base;
using base_type::base_type;
typename base_type::reference dereference() const
{
this->read_pending();
return this->current_[this->index_];
}
bool equal(const impl& other) const
{
return this->pos_ == other.pos_ && ((this->index_ | other.index_) & 3) == 0;
}
void increment()
{
this->read_pending();
++this->index_;
if (this->index_ == this->size_)
this->index_ = 4;
}
};
/*** forward iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf32_to_utf8_iterator_impl<impl, base_iterator, base_category,
enable_if_category< typename std::iterator_traits<base_iterator>::iterator_category, is_forward_tag>
, policies...> :
utf32_to_utf8_iterator_base<impl, base_iterator, base_category, uint8_t, const uint8_t&, policies...>
{
protected:
using base_type = typename utf32_to_utf8_iterator_impl::utf32_to_utf8_iterator_base;
using base_type::base_type;
};
/*** bidirectional & random access iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf32_to_utf8_iterator_impl<impl, base_iterator, base_category,
enable_if_category< typename std::iterator_traits<base_iterator>::iterator_category, is_bidirectional_tag, is_random_access_tag>
, policies...> :
utf32_to_utf8_iterator_base<impl, base_iterator, std::bidirectional_iterator_tag, uint8_t, const uint8_t&, policies...>
{
protected:
friend utf_iterator_access;
using base_type = typename utf32_to_utf8_iterator_impl::utf32_to_utf8_iterator_base;
using base_type::base_type;
using typename base_type::error_policy;
using typename base_type::from_policy;
void decrement()
{
if ((this->index_ & 3) == 0) {
this->size_ = base_type::read_prev(this->pos_, this->current_, error_policy(), from_policy());
this->index_ = this->size_;
}
--this->index_;
}
};
template <typename base_iterator, typename... policies>
class utf32_to_utf8_iterator :
public utf32_to_utf8_iterator_impl<
utf32_to_utf8_iterator<base_iterator, policies...>,
base_iterator,
typename std::iterator_traits<base_iterator>::iterator_category,
void, policies...
>
{
using impl_type = typename utf32_to_utf8_iterator::utf32_to_utf8_iterator_impl;
public:
utf32_to_utf8_iterator() {};
utf32_to_utf8_iterator(base_iterator pos) : impl_type(pos) {};
};
template <typename... policies, typename base_iterator>
auto make_utf32_to_utf8_iterator(base_iterator iter)
{
return utf32_to_utf8_iterator<base_iterator, policies...>{iter};
}
}
namespace utf
{
template <typename base_iterator, typename... policies>
class utf16_to_utf32_iterator;
UTF_POLICY_DEFAULT(utf16_to_utf32_iterator, onerror, throw_exception);
UTF_POLICY_DEFAULT(utf16_to_utf32_iterator, to, little_endian);
UTF_POLICY_DEFAULT(utf16_to_utf32_iterator, from, little_endian);
namespace detail {
template<uint32_t value,typename base_iterator, typename... Ts>
struct onerror_handler< utf16_to_utf32_iterator<base_iterator,Ts...>, replace_with<value>, void>
{
static uint32_t apply(const std::string& errmsg) {
return value;
}
};
template <typename base_iterator,typename... Ts>
struct onerror_handler< utf16_to_utf32_iterator<base_iterator,Ts...>, throw_exception, void>
{
static uint32_t apply(const std::string& errmsg) { throw std::runtime_error(errmsg); }
};
template<typename endianness,typename base_iterator, typename... Ts>
struct to_handler < utf16_to_utf32_iterator<base_iterator,Ts...>, endianness>
{
static uint32_t apply(uint32_t codepoint) {
return codepoint_as<endianness>(codepoint);
}
};
template<typename endianness,typename base_iterator, typename... Ts>
struct from_handler < utf16_to_utf32_iterator<base_iterator,Ts...>, endianness>
{
static uint16_t apply(uint16_t codeunit) {
return codeunit_as<native_endian,endianness>(codeunit);
}
};
}
/*** common iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename value_type, typename reference_type, typename... policies>
struct utf16_to_utf32_iterator_base :
utf_iterator< impl, base_iterator, base_category, value_type, reference_type>
{
protected:
utf16_to_utf32_iterator_base() {};
using base_type = typename utf16_to_utf32_iterator_base::utf_iterator;
friend utf_iterator_access;
using error_policy = select_policy_handler_t<impl, onerror, policies...>;
using from_policy = select_policy_handler_t<impl, from, policies...>;
using to_policy = select_policy_handler_t<impl, to, policies...>;
template < typename onerror_policy,typename from_policy, typename to_policy>
static uint32_t read_next_impl(base_iterator& pos, const base_iterator& end, onerror_policy, from_policy,to_policy, int8_t& replace, int8_t& consumed)
{
uint32_t value = from_policy::apply(*pos++); ++consumed;
if ((value & 0xFC00) == 0xD800)
{
if (pos == end)
return (replace=0,onerror_policy::apply("unexpected end of utf16 string"));
uint32_t lowsurrogate = from_policy::apply(*pos);
if ((lowsurrogate & 0xFC00) != 0xDC00)
return (replace=0,onerror_policy::apply("unpaired surrogate found"));
value = (value - 0xD7C0) << 10;
value |= (lowsurrogate & 0x3FF);
++pos; ++consumed;
}
else {
if ((value & 0xF800) == 0xD800)
return (replace=0,onerror_policy::apply("unpaired surrogate found"));
}
return value;
}
template <typename onerror_policy, typename from_policy,typename to_policy>
static uint32_t read_next(base_iterator& pos, const base_iterator& end, onerror_policy, from_policy,to_policy, int8_t& replace, int8_t& consumed)
{
consumed = 0;
replace = 0;
return to_policy::apply(read_next_impl(pos, end, onerror_policy(), from_policy(),to_policy(), replace, consumed));
}
template < typename onerror_policy, typename from_policy, typename to_policy>
static uint32_t read_prev_impl(base_iterator& pos,const base_iterator& start, onerror_policy, from_policy, to_policy, int8_t& replace, int8_t& consumed)
{
base_iterator prev(pos);
base_iterator end(pos);
uint16_t value = from_policy::apply(*--prev);
if ((value & 0xFC00) == 0xDC00) {
if (prev == start)
return (--pos, onerror_policy::apply("unexpected start of utf16 string"));
value = *--prev;
if ((value & 0xFC00) != 0xD800)
return (--pos, onerror_policy::apply("unexpected start of utf16 string"));
}
else if ((value & 0xF800) == 0xD800)
return (--pos,onerror_policy::apply("unpaired surrogate found"));
pos = prev;
return read_next_impl(prev, end, onerror_policy(),from_policy(), to_policy(), replace, consumed);
}
template < typename onerror_policy, typename from_policy, typename to_policy>
static uint32_t read_prev(base_iterator& pos, const base_iterator& start,onerror_policy, from_policy, to_policy, int8_t& replace, int8_t& consumed)
{
consumed = 0;
replace = 0;
return to_policy::apply(read_prev_impl(pos, start, onerror_policy(), from_policy(), to_policy(),replace,consumed));
}
utf16_to_utf32_iterator_base(base_iterator pos, const base_iterator end) :
pos_(pos),
end_(end),
current_(0),
replace_(0),
size_(2)
{};
typename base_type::reference dereference() const
{
if (!replace_ && read_required())
{
base_iterator pos(pos_);
read(pos);
}
return this->current_;
}
bool equal(const impl& other) const
{
return pos_ == other.pos_;
}
void increment()
{
if (replace_ > 0)
return (void)--replace_;
if (read_required())
read(pos_);
else
std::advance(pos_, size_);
size_ = 2;
}
bool read_required() const
{
return size_ == 2;
}
void read(base_iterator& pos) const
{
current_ = this->read_next(
pos,
end_,
error_policy(), from_policy(), to_policy(),
replace_,
size_
);
}
mutable base_iterator pos_;
base_iterator end_;
mutable uint32_t current_;
mutable int8_t size_;
mutable int8_t replace_;
};
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf16_to_utf32_iterator_impl;
///*** input iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf16_to_utf32_iterator_impl<impl, base_iterator, base_category,
enable_if_category< base_category, is_input_tag >
, policies...> :
utf16_to_utf32_iterator_base<impl, base_iterator, base_category, uint32_t, const uint32_t&, policies...>
{
protected:
using base_type = typename utf16_to_utf32_iterator_impl::utf16_to_utf32_iterator_base;
friend utf_iterator_access;
utf16_to_utf32_iterator_impl() {};
utf16_to_utf32_iterator_impl(base_iterator pos, const base_iterator end) :
base_type(pos, end)
{
this->size_ = 0;
if (pos != end)
this->read(this->pos_);
}
void increment()
{
if (this->replace_ > 0)
return (void)--this->replace_;
if (this->pos_ != this->end_)
this->read(this->pos_);
else
this->size_ = 0;
}
bool equal(const impl& other) const
{
return other.pos_ == this->pos_ && other.size_ == this->size_ && this->replace_ == other.replace_;
}
typename base_type::reference dereference() const
{
return this->current_;
}
};
/*** forward iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf16_to_utf32_iterator_impl<impl, base_iterator, base_category,
enable_if_category< base_category, is_forward_tag>, policies...>
: utf16_to_utf32_iterator_base<impl, base_iterator, base_category, uint32_t, const uint32_t&, policies...>
{
protected:
using base_type = typename utf16_to_utf32_iterator_impl::utf16_to_utf32_iterator_base;
using base_type::base_type;
};
/*** bidirectional & random access iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf16_to_utf32_iterator_impl<impl, base_iterator, base_category,
enable_if_category<
base_category, is_bidirectional_tag, is_random_access_tag>
, policies...> :
utf16_to_utf32_iterator_base<impl, base_iterator, std::bidirectional_iterator_tag, uint32_t, const uint32_t&, policies...>
{
protected:
using base_type = typename utf16_to_utf32_iterator_impl::utf16_to_utf32_iterator_base;
using typename base_type::error_policy;
using typename base_type::to_policy;
using typename base_type::from_policy;
friend utf_iterator_access;
utf16_to_utf32_iterator_impl() {};
utf16_to_utf32_iterator_impl(base_iterator pos,const base_iterator start, const base_iterator end) :
base_type(pos,end),
start_(start)
{};
void decrement()
{
if (this->replace_ < 0)
return (void)++this->replace_;
this->derived().current_ = this->read_prev(
this->pos_,
this->start_,
error_policy(), from_policy(),to_policy(),
this->replace_,
this->size_
);
}
base_iterator start_;
};
template <typename base_iterator, typename... policies>
class utf16_to_utf32_iterator :
public utf16_to_utf32_iterator_impl<
utf16_to_utf32_iterator<base_iterator, policies...>,
base_iterator,
typename std::iterator_traits<base_iterator>::iterator_category,
void, policies...
>
{
using impl_type = typename utf16_to_utf32_iterator::utf16_to_utf32_iterator_impl;
friend typename impl_type::base_type;
public:
utf16_to_utf32_iterator() {};
template<typename category_type=typename std::iterator_traits<base_iterator>::iterator_category,
typename bidirectional_or_random_access = enable_if_category<category_type, is_bidirectional_tag, is_random_access_tag>>
utf16_to_utf32_iterator(base_iterator pos, base_iterator start, base_iterator end) : impl_type(pos, start, end) {}
template<typename category_type=typename std::iterator_traits<base_iterator>::iterator_category,
typename input_or_forward = enable_if_category<category_type, is_input_tag, is_forward_tag>>
utf16_to_utf32_iterator(base_iterator pos, base_iterator end) : impl_type(pos, end) {}
};
template <typename... policies, typename base_iterator,
typename category_type = typename std::iterator_traits<base_iterator>::iterator_category,
enable_if_category_b<category_type, is_bidirectional_tag, is_random_access_tag> = true>
auto make_utf16_to_utf32_iterator(base_iterator begin, base_iterator end)
{
return utf16_to_utf32_iterator<base_iterator, policies...>{begin, begin, end};
}
template <typename... policies, typename base_iterator,
typename category_type = typename std::iterator_traits<base_iterator>::iterator_category,
enable_if_category_b<category_type, is_input_tag, is_forward_tag> = true>
auto make_utf16_to_utf32_iterator(base_iterator begin, base_iterator end)
{
return utf16_to_utf32_iterator<base_iterator, policies...>{begin, end};
}
}
namespace utf
{
template <typename base_iterator, typename... policies>
class utf32_to_utf16_iterator;
UTF_POLICY_DEFAULT(utf32_to_utf16_iterator, onerror, throw_exception);
UTF_POLICY_DEFAULT(utf32_to_utf16_iterator, from, little_endian);
UTF_POLICY_DEFAULT(utf32_to_utf16_iterator, to, little_endian);
namespace detail {
template<uint32_t value, typename base_iterator, typename... Ts>
struct onerror_handler< utf32_to_utf16_iterator<base_iterator,Ts...>, replace_with<value>, void>
{
static uint32_t apply(const std::string& errmsg, uint32_t& codepoint) {
return codepoint = value;
}
};
template <typename base_iterator, typename... Ts>
struct onerror_handler< utf32_to_utf16_iterator<base_iterator,Ts...>, throw_exception, void>
{
static uint32_t apply(const std::string& errmsg, uint32_t& codepoint) {
throw std::runtime_error(errmsg);
}
};
template<typename endianness,typename base_iterator, typename... Ts>
struct to_handler < utf32_to_utf16_iterator<base_iterator,Ts...>, endianness>
{
static uint16_t apply(uint16_t codeunit) {
return codeunit_as<endianness>(codeunit);
}
};
template<typename endianness,typename base_iterator, typename... Ts>
struct from_handler < utf32_to_utf16_iterator<base_iterator,Ts...>, endianness>
{
static uint32_t apply(uint32_t codepoint) {
return codepoint_as<native_endian, endianness>(codepoint);
}
};
}
/*** common iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename value_type, typename reference_type, typename... policies>
struct utf32_to_utf16_iterator_base :
utf_iterator< impl, base_iterator, base_category, value_type, reference_type>
{
friend utf_iterator_access;
protected:
utf32_to_utf16_iterator_base() {};
utf32_to_utf16_iterator_base(base_iterator pos) :
current_{ 0 },
size_(0),
index_(2),
pos_(pos)
{}
using error_policy = select_policy_handler_t<impl, onerror, policies...>;
using from_policy = select_policy_handler_t<impl, from, policies...>;
using to_policy = select_policy_handler_t<impl, to, policies...>;
template <typename onerror_policy, typename from_policy,typename to_policy>
static size_t read_next(base_iterator& pos, uint16_t* bytes, onerror_policy, from_policy, to_policy)
{
uint32_t codepoint = from_policy::apply(*pos++);
size_t size = 0;
if (codepoint > 0x10FFFF)
codepoint = onerror_policy::apply("error encoding utf16 string, invalid codepoint.", codepoint);
if (codepoint >= 0x10000)
{
bytes[0] = static_cast<uint16_t>(codepoint >> 10) + 0xD7C0;
bytes[1] = static_cast<uint16_t>(codepoint & 0x3FF) + 0xDC00;
size = 2;
}
else
{
if ((codepoint & 0xFFFFF800) == 0xD800)
codepoint = onerror_policy::apply("error encoding utf16 string, invalid surrogate codepoint.", codepoint);
bytes[0] = static_cast<uint16_t>(codepoint);
bytes[1] = 0;
size = 1;
}
for (size_t i = 0; i < size; ++i)
bytes[i] = to_policy::apply(bytes[i]);
return size;
}
template < typename onerror_policy, typename from_policy, typename to_policy>
static size_t read_prev(base_iterator& pos, uint16_t* bytes, onerror_policy, from_policy,to_policy)
{
base_iterator prev(--pos);
return read_next(prev, bytes, onerror_policy(), from_policy(), to_policy());
}
using base_type = typename utf32_to_utf16_iterator_base::utf_iterator;
using base_type::base_type;
typename base_type::reference dereference() const
{
read_pending();
return this->current_[this->index_];
}
bool equal(const impl& other) const
{
return this->pos_ == other.pos_ && ((this->index_ | other.index_) & 1) == 0;
}
void increment()
{
read_pending();
++this->index_;
if (this->index_ == this->size_)
this->index_ = 2;
}
inline void read_pending() const
{
if (this->index_ == 2) {
this->size_ = read_next(this->pos_, this->current_, error_policy(), from_policy(), to_policy());
this->index_ = 0;
}
}
mutable uint16_t current_[2];
mutable size_t index_;
mutable size_t size_;
mutable base_iterator pos_;
};
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf32_to_utf16_iterator_impl;
/*** input iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf32_to_utf16_iterator_impl<impl, base_iterator, base_category,
enable_if_category< typename std::iterator_traits<base_iterator>::iterator_category, is_input_tag>
, policies...> :
utf32_to_utf16_iterator_base<impl, base_iterator, base_category, uint16_t, const uint16_t&, policies...>
{
protected:
struct postfix_increment_result_type {
postfix_increment_result_type(const impl& iter) :
value_(*iter)
{}
uint16_t operator*() const { return value_; }
private:
uint16_t value_;
};
friend utf_iterator_access;
using base_type = typename utf32_to_utf16_iterator_impl::utf32_to_utf16_iterator_base;
using base_type::base_type;
typename base_type::reference dereference() const
{
this->read_pending();
return this->current_[this->index_];
}
bool equal(const impl& other) const
{
return this->pos_ == other.pos_ && ((this->index_ | other.index_) & 1) == 0;
}
void increment()
{
this->read_pending();
++this->index_;
if (this->index_ == this->size_)
this->index_ = 2;
}
};
/*** forward iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf32_to_utf16_iterator_impl<impl, base_iterator, base_category,
enable_if_category< typename std::iterator_traits<base_iterator>::iterator_category, is_forward_tag>
, policies...> :
utf32_to_utf16_iterator_base<impl, base_iterator, base_category, uint16_t, const uint16_t&, policies...>
{
protected:
using base_type = typename utf32_to_utf16_iterator_impl::utf32_to_utf16_iterator_base;
using base_type::base_type;
};
/*** bidirectional & random access iterator implementation */
template <typename impl, typename base_iterator, typename base_category, typename... policies>
struct utf32_to_utf16_iterator_impl<impl, base_iterator, base_category,
enable_if_category< typename std::iterator_traits<base_iterator>::iterator_category, is_bidirectional_tag, is_random_access_tag>
, policies...> :
utf32_to_utf16_iterator_base<impl, base_iterator, std::bidirectional_iterator_tag, uint16_t, const uint16_t&, policies...>
{
protected:
friend utf_iterator_access;
using base_type = typename utf32_to_utf16_iterator_impl::utf32_to_utf16_iterator_base;
using base_type::base_type;
using typename base_type::error_policy;
using typename base_type::from_policy;
using typename base_type::to_policy;
void decrement()
{
if ((this->index_ & 1) == 0) {
this->size_ = base_type::read_prev(this->pos_, this->current_, error_policy(), from_policy(), to_policy());
this->index_ = this->size_;
}
--this->index_;
}
};
template <typename base_iterator, typename... policies>
class utf32_to_utf16_iterator :
public utf32_to_utf16_iterator_impl<
utf32_to_utf16_iterator<base_iterator, policies...>,
base_iterator,
typename std::iterator_traits<base_iterator>::iterator_category,
void, policies...
>
{
using impl_type = typename utf32_to_utf16_iterator::utf32_to_utf16_iterator_impl;
public:
utf32_to_utf16_iterator() {};
utf32_to_utf16_iterator(base_iterator pos) : impl_type(pos) {};
};
template <typename... policies, typename base_iterator>
auto make_utf32_to_utf16_iterator(base_iterator iter)
{
return utf32_to_utf16_iterator<base_iterator, policies...>{iter};
}
}
namespace utf
{
template <typename T,typename base_iterator>
class bytes_to_type_iterator;
/*** common iterator implementation */
template <typename T,typename impl, typename base_iterator, typename impl_catagory, typename value_type, typename reference_type>
struct bytes_to_type_iterator_base :
utf_iterator< impl, base_iterator, impl_catagory, value_type, reference_type>
{
protected:
using base_type = typename bytes_to_type_iterator_base::utf_iterator;
friend utf_iterator_access;
bytes_to_type_iterator_base() {};
bytes_to_type_iterator_base(base_iterator pos, const base_iterator end) :
pos_(pos),
end_(end),
current_(0),
pending_(true)
{
};
typename base_type::reference dereference() const
{
if (pending_) {
base_iterator pos(pos_);
read_next(pos, end_);
}
return current_;
}
bool equal(const impl& other) const
{
return pos_ == other.pos_;
}
void increment()
{
for (size_t i = 0; i < sizeof(T); ++i,++pos_) {
if (pos_ == end_)
throw std::runtime_error("invalid byte count, byte count must be divisbile by 2");
}
pending_ = true;
}
void read_next(base_iterator& pos, base_iterator end) const
{
current_ = 0;
for (size_t i = 0; i < sizeof(T); ++i)
{
if (pos == end)
throw std::runtime_error("invalid byte count, byte count must be divisbile by 2");
auto val = static_cast<typename std::make_unsigned<typename base_iterator::value_type>::type>(*pos++);
current_ |= val << (8 * i);
}
}
mutable base_iterator pos_;
mutable bool pending_;
base_iterator end_;
mutable T current_;
};
template <typename T,typename impl, typename base_iterator, typename base_category,typename enable=void>
struct bytes_to_type_iterator_impl;
/*** input iterator implementation */
template <typename T,typename impl, typename base_iterator, typename base_category>
struct bytes_to_type_iterator_impl<T,impl, base_iterator, base_category,
enable_if_category< base_category, is_input_tag >
> : bytes_to_type_iterator_base<T,impl, base_iterator, std::input_iterator_tag, T, const T&>
{
protected:
using base_type = typename bytes_to_type_iterator_impl::bytes_to_type_iterator_base;
friend utf_iterator_access;
bytes_to_type_iterator_impl()
{}
bytes_to_type_iterator_impl(base_iterator pos, const base_iterator end) :
base_type(pos, end)
{
if (pos != end)
{
this->read_next(this->pos_, this->end_);
this->pending_ = false;
}
}
void increment()
{
if (this->pos_ != this->end_)
this->read_next(this->pos_,this->end_);
else
this->pending_ = true;
}
bool equal(const impl& other) const
{
return this->pos_ == other.pos_ && this->pending_ == other.pending_;
}
typename base_type::reference dereference() const
{
return this->current_;
}
};
/*** forward/input iterator implementation */
template <typename T,typename impl, typename base_iterator, typename base_category>
struct bytes_to_type_iterator_impl<T,impl, base_iterator, base_category,
enable_if_category< base_category, is_forward_tag>>
: bytes_to_type_iterator_base<T,impl, base_iterator, base_category,T, const T&>
{
protected:
using base_type = typename bytes_to_type_iterator_impl::bytes_to_type_iterator_base;
using base_type::base_type;
};
/*** bidirectional & random access iterator implementation */
template <typename T,typename impl, typename base_iterator, typename base_category>
struct bytes_to_type_iterator_impl<T,impl, base_iterator, base_category,
enable_if_category<base_category, is_bidirectional_tag, is_random_access_tag>
> : bytes_to_type_iterator_base<T,impl, base_iterator, std::bidirectional_iterator_tag, T, const T&>
{
protected:
friend utf_iterator_access;
using base_type = typename bytes_to_type_iterator_impl::bytes_to_type_iterator_base;
bytes_to_type_iterator_impl()
{}
bytes_to_type_iterator_impl(base_iterator pos, base_iterator start, base_iterator end) :
base_type(pos, end),
start_(start)
{}
void decrement()
{
this->current_ = 0;
for (size_t i = 0; i < sizeof(T); ++i, --this->pos_){
if (this->pos_ == start_)
throw std::runtime_error("invalid byte count, byte count must be divisbile by 2");
}
}
base_iterator start_;
};
template <typename T,typename base_iterator>
class bytes_to_type_iterator :
public bytes_to_type_iterator_impl<T,bytes_to_type_iterator<T,base_iterator>,base_iterator,typename std::iterator_traits<base_iterator>::iterator_category>
{
using impl_type = typename bytes_to_type_iterator::bytes_to_type_iterator_impl;
friend typename impl_type::base_type;
public:
bytes_to_type_iterator() {};
template<typename category_type = typename std::iterator_traits<base_iterator>::iterator_category,
typename bidirectional_or_random_access = enable_if_category<category_type, is_bidirectional_tag, is_random_access_tag>>
bytes_to_type_iterator(base_iterator pos, base_iterator start, base_iterator end) : impl_type(pos, start, end) {}
template<typename category_type = typename std::iterator_traits<base_iterator>::iterator_category,
typename input_or_forward = enable_if_category<category_type, is_input_tag, is_forward_tag>>
bytes_to_type_iterator(base_iterator pos, base_iterator end) : impl_type(pos, end) {}
};
template <typename base_iterator>
using bytes_to_short_iterator = bytes_to_type_iterator<uint16_t, base_iterator>;
template <typename base_iterator>
using bytes_to_long_iterator = bytes_to_type_iterator<uint32_t, base_iterator>;
template<typename base_iterator,
typename category_type = typename std::iterator_traits<base_iterator>::iterator_category,
enable_if_category_b<category_type, is_bidirectional_tag, is_random_access_tag> = true>
auto make_bytes_to_long_iterator(base_iterator start, base_iterator end)
{
return bytes_to_long_iterator<base_iterator>(start, start, end);
}
template<typename base_iterator,
typename category_type = typename std::iterator_traits<base_iterator>::iterator_category,
enable_if_category_b<category_type, is_input_tag, is_forward_tag> = true>
auto make_bytes_to_long_iterator(base_iterator start, base_iterator end)
{
return bytes_to_long_iterator<base_iterator>(start, end);
}
template<typename base_iterator,
typename category_type = typename std::iterator_traits<base_iterator>::iterator_category,
enable_if_category_b<category_type, is_bidirectional_tag, is_random_access_tag> = true>
auto make_bytes_to_short_iterator(base_iterator start, base_iterator end)
{
return bytes_to_short_iterator<base_iterator>(start, start, end);
}
template<typename base_iterator,
typename category_type = typename std::iterator_traits<base_iterator>::iterator_category,
enable_if_category_b<category_type, is_input_tag, is_forward_tag> = true>
auto make_bytes_to_short_iterator(base_iterator start, base_iterator end)
{
return bytes_to_short_iterator<base_iterator>(start, end);
}
}
namespace utf
{
template <typename T>
struct result_type : type_c<T> {};
namespace detail
{
template <typename T>
using is_error_policy = bool_c< is_instance_of_template<onerror, T>::value >;
template <typename T>
using is_result_type = bool_c< has_begin_end<T>::value && has_value_type<T>::value>;
template<typename iterator_type,
typename base_iterator,
typename iterator_category = typename std::iterator_traits< iterator_type >::iterator_category,
typename std::enable_if<
category_any_of<iterator_category, is_forward_tag, is_input_tag> &&
(sizeof(typename iterator_type::value_type) > sizeof(typename base_iterator::value_type))
, bool>::type = true>
std::tuple<iterator_type, iterator_type> make_utf_iterators_for_iterable( base_iterator begin, base_iterator end)
{
return std::make_pair(iterator_type{ begin,end }, iterator_type{ end,end });
}
template<typename iterator_type,
typename base_iterator,
typename iterator_category = typename std::iterator_traits< iterator_type >::iterator_category,
typename std::enable_if<
category_any_of<iterator_category, is_bidirectional_tag, is_random_access_tag> &&
(sizeof(typename iterator_type::value_type) > sizeof(typename base_iterator::value_type))
, bool>::type = true>
std::tuple<iterator_type, iterator_type> make_utf_iterators_for_iterable(base_iterator begin, base_iterator end)
{
return std::make_pair(iterator_type{ begin,begin,end }, iterator_type{ end,begin,end });
}
template<typename iterator_type,
typename base_iterator,
typename std::enable_if< (sizeof(typename iterator_type::value_type) < sizeof(typename base_iterator::value_type))
, bool>::type = true>
std::tuple<iterator_type, iterator_type> make_utf_iterators_for_iterable(base_iterator begin, base_iterator end)
{
return std::make_pair(iterator_type{ begin }, iterator_type{ end });
}
template < template <typename...> class iterator_tmpl, typename result_type, typename base_iterator, typename... policy>
result_type utfn_to_utfm(base_iterator begin, base_iterator end, type_list< policy...>)
{
using iterator_type = iterator_tmpl<base_iterator, policy...>;
iterator_type upos, uend;
std::tie(upos, uend) = detail::make_utf_iterators_for_iterable<iterator_type>(begin,end);
result_type result;
std::copy(upos, uend, std::back_inserter(result));
return result;
}
template < template <typename...> class iterator_tmpl_first, template <typename...> class iterator_tmpl_second, typename result_type, typename base_iterator, typename... policy>
result_type utfn_to_utfm(base_iterator begin, base_iterator end, type_list< policy...>)
{
using error_policy = select_argument_or_default_t< is_error_policy, void, policy...>;
using iterator_type_first = iterator_tmpl_first<base_iterator, error_policy>;
iterator_type_first uposf, uendf;
std::tie(uposf, uendf) = detail::make_utf_iterators_for_iterable<iterator_type_first>(begin, end);
using iterator_type_second = iterator_tmpl_second<iterator_type_first, error_policy, policy...>;
iterator_type_second uposs, uends;
std::tie(uposs, uends) = detail::make_utf_iterators_for_iterable<iterator_type_second>(uposf, uendf);
result_type result;
std::copy(uposs, uends, std::back_inserter(result));
return result;
}
}
template <typename... arguments,typename iterator_type>
auto utf8_to_utf32(iterator_type begin, iterator_type end)
{
using result_type = select_argument_or_default_t<detail::is_result_type, u32string, arguments...>;
return detail::utfn_to_utfm< utf8_to_utf32_iterator, result_type>(begin,end,type_list<arguments...>());
}
template <typename... Ts,typename source_type>
auto utf8_to_utf32(const source_type& src)
{
return utf8_to_utf32<Ts...>(src.begin(), src.end());
}
template <typename... arguments, typename iterator_type>
auto utf32_to_utf8(iterator_type begin, iterator_type end)
{
using result_type = select_argument_or_default_t<detail::is_result_type, u8string, arguments...>;
return detail::utfn_to_utfm< utf32_to_utf8_iterator, result_type>(begin, end, type_list<arguments...>());
}
template <typename... Ts, typename source_type>
auto utf32_to_utf8(const source_type& src)
{
return utf32_to_utf8<Ts...>(src.begin(), src.end());
}
template <typename... arguments, typename iterator_type>
auto utf16_to_utf32(iterator_type begin, iterator_type end)
{
using result_type = select_argument_or_default_t<detail::is_result_type, u32string, arguments...>;
return detail::utfn_to_utfm< utf16_to_utf32_iterator, result_type>(begin, end, type_list<arguments...>());
}
template <typename... Ts, typename source_type>
auto utf16_to_utf32(const source_type& src)
{
return utf16_to_utf32<Ts...>(src.begin(), src.end());
}
template <typename... arguments, typename iterator_type>
auto utf32_to_utf16(iterator_type begin, iterator_type end)
{
using result_type = select_argument_or_default_t<detail::is_result_type, u16string, arguments...>;
return detail::utfn_to_utfm< utf32_to_utf16_iterator, result_type>(begin, end, type_list<arguments...>());
}
template <typename... Ts, typename source_type>
auto utf32_to_utf16(const source_type& src)
{
return utf32_to_utf16<Ts...>(src.begin(), src.end());
}
template <typename... arguments, typename base_iterator>
auto utf8_to_utf16(base_iterator begin, base_iterator end)
{
using result_type = select_argument_or_default_t<detail::is_result_type, u16string, arguments...>;
return detail::utfn_to_utfm< utf8_to_utf32_iterator, utf32_to_utf16_iterator, result_type>(begin, end, type_list<arguments...>());
}
template <typename... Ts, typename source_type>
auto utf8_to_utf16(const source_type& src)
{
return utf8_to_utf16<Ts...>(src.begin(), src.end());
}
template <typename... arguments, typename base_iterator>
auto utf16_to_utf8(base_iterator begin, base_iterator end)
{
using result_type = select_argument_or_default_t<detail::is_result_type, u8string, arguments...>;
return detail::utfn_to_utfm< utf16_to_utf32_iterator, utf32_to_utf8_iterator, result_type>(begin, end, type_list<arguments...>());
}
template <typename... Ts, typename source_type>
auto utf16_to_utf8(const source_type& src)
{
return utf16_to_utf8<Ts...>(src.begin(), src.end());
}
/*** Potential ambiguity with utf16 and utf32 if the utf16 string
starts with two null characters it would be detected as utf32. */
template <typename iterator_type>
bom_type detect_bom(iterator_type pos, iterator_type end)
{
size_t byte_count = 0;
uint8_t bytes[4]{};
for (; byte_count < 4; ++pos) {
if (pos == end) break;
typename iterator_type::value_type value = *pos;
std::memcpy(bytes + byte_count, &value, sizeof(value));
byte_count += sizeof(value);
}
if (byte_count > 2 && !std::memcmp(bytes, utf8_bom, 3))
return bom_type::utf8;
if (byte_count > 3 && !std::memcmp(bytes, utf32_little_endian_bom, 4))
return bom_type::utf32_little_endian;
if (byte_count > 3 && !std::memcmp(bytes, utf32_big_endian_bom, 4))
return bom_type::utf32_big_endian;
if (byte_count > 1 && !std::memcmp(bytes, utf16_little_endian_bom, 2))
return bom_type::utf16_little_endian;
if (byte_count > 1 && !std::memcmp(bytes, utf16_big_endian_bom, 2))
return bom_type::utf16_big_endian;
return bom_type::none;
}
}
|
kublaios/SwiftyOnboard | Example/Pods/Target Support Files/SwiftyOnboard/SwiftyOnboard-umbrella.h | #ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "SwiftyOnboard.h"
FOUNDATION_EXPORT double SwiftyOnboardVersionNumber;
FOUNDATION_EXPORT const unsigned char SwiftyOnboardVersionString[];
|
ChopinDavid/UpsellViewController | UpsellViewController/UpsellViewController.h | //
// UpsellViewController.h
// UpsellViewController
//
// Created by <NAME> on 2/11/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for UpsellViewController.
FOUNDATION_EXPORT double UpsellViewControllerVersionNumber;
//! Project version string for UpsellViewController.
FOUNDATION_EXPORT const unsigned char UpsellViewControllerVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <UpsellViewController/PublicHeader.h>
|
varung2/raytracing.github.io | src/InOneWeekend/triangle.h | #ifndef TRIANGLE_H
#define TRIANGLE_H
#include "rtweekend.h"
#include "hittable.h"
class triangle : public hittable {
public:
triangle() : enable_vertex_norms(false) {}
triangle(const vec3& A, const vec3& B, const vec3& C,
const vec3& A_norm, const vec3& B_norm, const vec3& C_norm,
const shared_ptr<material> m) : enable_vertex_norms(true) {
corner = A;
BA = B - A;
CB = C - B;
AC = A - C;
normal = unit_vector(cross(BA, CB));
a = A; b = B; c = C;
mat_ptr = m;
a_norm = A_norm;
b_norm = B_norm;
c_norm = C_norm;
inv_ABC_area = 1.0/dot(normal, cross(BA, -AC));
}
triangle(const vec3& A, const vec3& B, const vec3& C, const shared_ptr<material> m) : enable_vertex_norms(false) {//specify the points
corner = A;
BA = B - A;
CB = C - B;
AC = A - C;
normal = unit_vector(cross(BA, CB));
a = A; b = B; c = C;
mat_ptr = m;
}
virtual bool hit(const ray& r, double tmin, double tmax, hit_record &hit) const override;
//member variables
public:
vec3 a, b, c; //points
vec3 AC, BA, CB, normal, corner; //vectors
shared_ptr<material> mat_ptr;
// point normals
vec3 a_norm, b_norm, c_norm;
private:
const bool enable_vertex_norms;
double inv_ABC_area;
};
/** Function: hit(...)
Description: Inherited hit function from parent. Checks if the ray has hit the object
Inputs:
r (type:ray) - casted ray that is checked against the geometry primitive
t_min (type:double) - time minimum
t_max (type:double) - time maximum
rec (type:hit_record) - record struct used to keep track of hit information if a hit is detected
Outputs:
bool (type:boolean) - returns if it hit something or not.
**/
bool triangle::hit(const ray& r, double tmin, double tmax, hit_record &rec) const {
//calculate intersection using barycentric coordinates
//First calculate the point of intersection on the plane
double x = dot(normal, r.direction());
if (fabs(x) < 0.001) return false;
double t = (dot(corner - r.origin(), normal)/x);
if (t < tmin || t > tmax) return false;
vec3 p = r.at(t);
vec3 AP = p - a;
vec3 CP = p - c;
vec3 BP = p - b;
//topleft
vec3 t0 = cross(BA, AP);
double ABP_area = dot(normal, t0);
if (ABP_area < 0) return false;
//topright
vec3 t1 = cross(CB, BP);
double BCP_area = dot(normal, t1);
if (BCP_area < 0) return false;
//bottom
vec3 t2 = cross(AC, CP);
if (dot(normal, t2) < 0) return false;
if (t < tmax && t > tmin) {
rec.t = t;
rec.p = p;
rec.mat_ptr = mat_ptr;
if (enable_vertex_norms) {
vec3 smoothed_normal;
double bary_a = BCP_area*inv_ABC_area;
double bary_c = ABP_area*inv_ABC_area;
smoothed_normal = unit_vector(bary_a*a_norm + (1.0 - bary_a - bary_c)*b_norm + bary_c*c_norm);
// Bug fix 1: fixed color at the edges (normal can be facing away from the ray direction after smoothing)
// - this causes a black color pixel because the scatter direction goes inside the object (only fixed lambertian shading)
// Bug 2: getting dark artifacts on edges of metal objects
// - fix attempt 1: if the regular normal is facing the correct direction and the smooth is also, then use the smooth normal
// otherwise, use the regular face normal (not working...)
// bool front_face_regular = dot(r.direction(), normal) < 0;
// bool front_face_smooth = dot(r.direction(), smoothed_normal) < 0;
// smoothed_normal = (front_face_regular && front_face_smooth) ? smoothed_normal : normal;
// smoothed_normal = (dot(r.direction(), smoothed_normal) < 0) ? smoothed_normal : normal;
// if the smoothed normal is pointing in the right direction - use it
if (dot(r.direction(), smoothed_normal) < 0) rec.normal = smoothed_normal;
else rec.set_face_normal(r, normal); //else set the normal to the regular face normal (w.r.t its orientation)
} else rec.set_face_normal(r, normal);
return true;
}
return false;
}
#endif |
q-barbar/esp-homekit-devices | libs/led_codes/led_codes.c | /*
* LED Codes
*
* Copyright 2018 <NAME> (@RavenSystem)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <esp8266.h>
#include <FreeRTOS.h>
#include <etstimer.h>
#include <esplibs/libmain.h>
#include "led_codes.h"
#define DURATION_OFF 150
typedef struct led_params_t {
blinking_params_t blinking_params;
uint8_t gpio;
bool status;
ETSTimer timer;
uint8_t count;
uint32_t delay;
} led_params_t;
led_params_t led_params;
void led_code_run() {
led_params.status = !led_params.status;
gpio_write(led_params.gpio, led_params.status);
if (led_params.status == 0) {
led_params.delay = (led_params.blinking_params.duration * 1000) + 90;
} else {
led_params.delay = DURATION_OFF;
led_params.count++;
}
sdk_os_timer_disarm(&led_params.timer);
if (led_params.count < led_params.blinking_params.times) {
sdk_os_timer_arm(&led_params.timer, led_params.delay, 0);
}
}
void led_code(uint8_t gpio, blinking_params_t blinking_params) {
led_params.gpio = gpio;
led_params.blinking_params = blinking_params;
sdk_os_timer_disarm(&led_params.timer);
sdk_os_timer_setfn(&led_params.timer, led_code_run, NULL);
led_params.status = 1;
led_params.count = 0;
led_code_run();
}
|
q-barbar/esp-homekit-devices | external_libs/homekit/src/json.h | #pragma once
#include <stdbool.h>
struct json_stream;
typedef struct json_stream json_stream;
typedef void (*json_flush_callback)(uint8_t *buffer, size_t size, void *context);
json_stream *json_new(size_t buffer_size, json_flush_callback on_flush, void *context);
void json_free(json_stream *json);
void json_flush(json_stream *json);
void json_object_start(json_stream *json);
void json_object_end(json_stream *json);
void json_array_start(json_stream *json);
void json_array_end(json_stream *json);
void json_integer(json_stream *json, long long x);
void json_float(json_stream *json, float x);
void json_string(json_stream *json, const char *x);
void json_boolean(json_stream *json, bool x);
void json_null(json_stream *json);
|
q-barbar/esp-homekit-devices | external_libs/wolfssl/user_settings.h | #ifndef wolfcrypt_user_settings_h
#define wolfcrypt_user_settings_h
#include <esp/hwrand.h>
static inline int hwrand_generate_block(uint8_t *buf, size_t len) {
hwrand_fill(buf, len);
return 0;
}
#define FREERTOS
#define WC_NO_HARDEN
#define NO_WOLFSSL_DIR
#define SINGLE_THREADED
#define WOLFSSL_LWIP
#define NO_INLINE
#define NO_WOLFSSL_MEMORY
#define NO_WOLFSSL_SMALL_STACK
#define MP_LOW_MEM
#define CUSTOM_RAND_GENERATE_BLOCK hwrand_generate_block
#endif
|
q-barbar/esp-homekit-devices | devices/KellyTron/main.c | <filename>devices/KellyTron/main.c
/*
* KellyTron
*
* v0.0.1
*
* Copyright 2018 <NAME> (@RavenSystem)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <esp/uart.h>
#include <esp8266.h>
#include <FreeRTOS.h>
#include <espressif/esp_wifi.h>
#include <espressif/esp_common.h>
#include <rboot-api.h>
#include <sysparam.h>
#include <task.h>
#include <etstimer.h>
#include <esplibs/libmain.h>
#include <homekit/homekit.h>
#include <homekit/characteristics.h>
#include <wifi_config.h>
#include "../common/custom_characteristics.h"
#define TOGGLE_GPIO 5
#define RELAY_GPIO 4
#define DISABLED_TIME 50
static volatile uint32_t last_press_time;
static ETSTimer device_restart_timer, change_settings_timer, extra_func_timer;
void switch1_on_callback(homekit_value_t value);
homekit_value_t read_switch1_on_callback();
void change_settings_callback();
void show_setup_callback();
void ota_firmware_callback();
void on_wifi_ready();
homekit_characteristic_t switch1_on = HOMEKIT_CHARACTERISTIC_(ON, false, .getter=read_switch1_on_callback, .setter=switch1_on_callback);
homekit_characteristic_t show_setup = HOMEKIT_CHARACTERISTIC_(CUSTOM_SHOW_SETUP, false, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(show_setup_callback));
homekit_characteristic_t reboot_device = HOMEKIT_CHARACTERISTIC_(CUSTOM_REBOOT_DEVICE, false, .id=103, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(ota_firmware_callback));
homekit_characteristic_t ota_firmware = HOMEKIT_CHARACTERISTIC_(CUSTOM_OTA_UPDATE, false, .id=110, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(ota_firmware_callback));
void relay_write(bool on, int gpio) {
last_press_time = xTaskGetTickCountFromISR() + (DISABLED_TIME / portTICK_PERIOD_MS);
gpio_write(gpio, on ? 1 : 0);
}
void save_settings() {
sysparam_status_t status;
bool bool_value;
status = sysparam_get_bool("show_setup", &bool_value);
if (status == SYSPARAM_OK && bool_value != show_setup.value.bool_value) {
sysparam_set_bool("show_setup", show_setup.value.bool_value);
}
}
void device_restart_task() {
vTaskDelay(5500 / portTICK_PERIOD_MS);
if (ota_firmware.value.bool_value) {
rboot_set_temp_rom(1);
}
sdk_system_restart();
vTaskDelete(NULL);
}
void device_restart() {
printf(">>> Restarting device\n");
xTaskCreate(device_restart_task, "device_restart_task", 256, NULL, 1, NULL);
}
void show_setup_callback() {
if (show_setup.value.bool_value) {
sdk_os_timer_setfn(&device_restart_timer, device_restart, NULL);
sdk_os_timer_arm(&device_restart_timer, 5000, 0);
} else {
sdk_os_timer_disarm(&device_restart_timer);
}
save_settings();
}
void reset_call_task() {
printf(">>> Resetting device to factory defaults\n");
vTaskDelay(100 / portTICK_PERIOD_MS);
sysparam_set_bool("show_setup", false);
vTaskDelay(100 / portTICK_PERIOD_MS);
homekit_server_reset();
vTaskDelay(500 / portTICK_PERIOD_MS);
wifi_config_reset();
vTaskDelay(500 / portTICK_PERIOD_MS);
sdk_system_restart();
vTaskDelete(NULL);
}
void reset_call(const uint8_t gpio) {
relay_write(false, RELAY1_GPIO);
gpio_disable(RELAY1_GPIO);
xTaskCreate(reset_call_task, "reset_call_task", 256, NULL, 1, NULL);
}
void ota_firmware_callback() {
if (ota_firmware.value.bool_value || reboot_device.value.bool_value) {
sdk_os_timer_setfn(&device_restart_timer, device_restart, NULL);
sdk_os_timer_arm(&device_restart_timer, 5000, 0);
} else {
sdk_os_timer_disarm(&device_restart_timer);
}
}
void change_settings_callback() {
sdk_os_timer_disarm(&change_settings_timer);
sdk_os_timer_arm(&change_settings_timer, 3000, 0);
}
void switch1_on_callback(homekit_value_t value) {
printf(">>> Toggle Switch 1\n");
switch1_on.value = value;
relay_write(switch1_on.value.bool_value, RELAY_GPIO);
printf(">>> Relay 1 -> %i\n", switch1_on.value.bool_value);
}
homekit_value_t read_switch1_on_callback() {
return switch1_on.value;
}
void toggle_switch(const uint8_t gpio) {
printf(">>> Toggle Switch manual\n");
switch1_on.value.bool_value = !switch1_on.value.bool_value;
relay_write(switch1_on.value.bool_value, RELAY_GPIO);
printf(">>> Relay 1 -> %i\n", switch1_on.value.bool_value);
homekit_characteristic_notify(&switch1_on, switch1_on.value);
}
void identify(homekit_value_t _value) {
printf(">>> Identify\n");
}
void gpio_init() {
sysparam_status_t status;
bool bool_value;
status = sysparam_get_bool("show_setup", &bool_value);
if (status == SYSPARAM_OK) {
show_setup.value.bool_value = bool_value;
printf(">>> Loading show_setup -> %i\n", show_setup.value.bool_value);
} else {
sysparam_set_bool("show_setup", false);
printf(">>> Setting show_setup to default -> false\n");
}
printf(">>> Loading device gpio settings\n");
gpio_enable(TOGGLE_GPIO, GPIO_INPUT);
gpio_set_pullup(TOGGLE_GPIO->gpio, false, false);
gpio_enable(RELAY_GPIO, GPIO_OUTPUT);
relay_write(switch1_on.value.bool_value, RELAY_GPIO);
sdk_os_timer_setfn(&change_settings_timer, save_settings, NULL);
wifi_config_init("KellyTron", NULL, on_wifi_ready);
}
homekit_characteristic_t name = HOMEKIT_CHARACTERISTIC_(NAME, NULL);
homekit_characteristic_t manufacturer = HOMEKIT_CHARACTERISTIC_(MANUFACTURER, "RavenSystem");
homekit_characteristic_t serial = HOMEKIT_CHARACTERISTIC_(SERIAL_NUMBER, NULL);
homekit_characteristic_t model = HOMEKIT_CHARACTERISTIC_(MODEL, "KellyTron");
homekit_characteristic_t identify_function = HOMEKIT_CHARACTERISTIC_(IDENTIFY, identify);
homekit_characteristic_t switch1_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Switch 1");
homekit_characteristic_t setup_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Setup", .id=100);
homekit_characteristic_t device_type_name = HOMEKIT_CHARACTERISTIC_(CUSTOM_DEVICE_TYPE_NAME, "Switch 1", .id=101);
homekit_characteristic_t firmware = HOMEKIT_CHARACTERISTIC_(FIRMWARE_REVISION, "0.0.1");
homekit_accessory_category_t accessory_category = homekit_accessory_category_switch;
void create_accessory_name() {
uint8_t macaddr[6];
sdk_wifi_get_macaddr(STATION_IF, macaddr);
char *name_value = malloc(17);
snprintf(name_value, 17, "KellyTron %02X%02X%02X", macaddr[3], macaddr[4], macaddr[5]);
name.value = HOMEKIT_STRING(name_value);
char *serial_value = malloc(13);
snprintf(serial_value, 13, "%02X%02X%02X%02X%02X%02X", macaddr[0], macaddr[1], macaddr[2], macaddr[3], macaddr[4], macaddr[5]);
serial.value = HOMEKIT_STRING(serial_value);
}
homekit_server_config_t config;
void create_accessory() {
uint8_t service_count = 3, service_number = 2;
// Total service count
if (show_setup.value.bool_value) {
service_count++;
}
homekit_accessory_t **accessories = calloc(2, sizeof(homekit_accessory_t*));
homekit_accessory_t *sonoff = accessories[0] = calloc(1, sizeof(homekit_accessory_t));
sonoff->id = 1;
sonoff->category = accessory_category;
sonoff->config_number = 000001; // Matches as example: firmware_revision 2.3.8 = 02.03.10 (octal) = config_number 020310
sonoff->services = calloc(service_count, sizeof(homekit_service_t*));
homekit_service_t *sonoff_info = sonoff->services[0] = calloc(1, sizeof(homekit_service_t));
sonoff_info->id = 1;
sonoff_info->type = HOMEKIT_SERVICE_ACCESSORY_INFORMATION;
sonoff_info->characteristics = calloc(7, sizeof(homekit_characteristic_t*));
sonoff_info->characteristics[0] = &name;
sonoff_info->characteristics[1] = &manufacturer;
sonoff_info->characteristics[2] = &serial;
sonoff_info->characteristics[3] = &model;
sonoff_info->characteristics[4] = &firmware;
sonoff_info->characteristics[5] = &identify_function;
printf(">>> Creating accessory\n");
char *device_type_name_value = malloc(9);
snprintf(device_type_name_value, 9, "Switch 1");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_switch1 = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_switch1->id = 8;
sonoff_switch1->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch1->primary = true;
sonoff_switch1->characteristics = calloc(4, sizeof(homekit_characteristic_t*));
sonoff_switch1->characteristics[0] = &switch1_service_name;
sonoff_switch1->characteristics[1] = &switch1_on;
sonoff_switch1->characteristics[2] = &show_setup;
// Setup Accessory, visible only in 3party Apps
if (show_setup.value.bool_value) {
homekit_service_t *sonoff_setup = sonoff->services[service_number] = calloc(1, sizeof(homekit_service_t));
sonoff_setup->id = 99;
sonoff_setup->type = HOMEKIT_SERVICE_CUSTOM_SETUP;
sonoff_setup->primary = false;
uint8_t setting_count = 4, setting_number = 3;
sysparam_status_t status;
char *char_value;
status = sysparam_get_string("ota_repo", &char_value);
if (status == SYSPARAM_OK) {
setting_count++;
}
sonoff_setup->characteristics = calloc(setting_count, sizeof(homekit_characteristic_t*));
sonoff_setup->characteristics[0] = &setup_service_name;
sonoff_setup->characteristics[1] = &device_type_name;
sonoff_setup->characteristics[2] = &reboot_device;
if (status == SYSPARAM_OK) {
sonoff_setup->characteristics[setting_number] = &ota_firmware;
setting_number++;
}
}
config.accessories = accessories;
config.password = "<PASSWORD>";
homekit_server_init(&config);
}
void on_wifi_ready() {
create_accessory_name();
create_accessory();
}
void user_init(void) {
uart_set_baud(0, 115200);
printf(">>> KellyTron firmware loaded\n");
printf(">>> Developed by RavenSystem - <NAME>\n");
printf(">>> Firmware revision: %s\n\n", firmware.value.string_value);
gpio_init();
}
|
q-barbar/esp-homekit-devices | external_libs/wifi_config/src/form_urlencoded.h | #pragma once
typedef struct _form_param {
char *name;
char *value;
struct _form_param *next;
} form_param_t;
form_param_t *form_params_parse(const char *s);
form_param_t *form_params_find(form_param_t *params, const char *name);
void form_params_free(form_param_t *params);
|
q-barbar/esp-homekit-devices | external_libs/homekit/src/tlv.h | #ifndef __TLV_H__
#define __TLV_H__
typedef unsigned char byte;
typedef struct _tlv {
struct _tlv *next;
byte type;
byte *value;
size_t size;
} tlv_t;
typedef struct {
tlv_t *head;
} tlv_values_t;
tlv_values_t *tlv_new();
void tlv_free(tlv_values_t *values);
int tlv_add_value(tlv_values_t *values, byte type, const byte *value, size_t size);
int tlv_add_string_value(tlv_values_t *values, byte type, const char *value);
int tlv_add_integer_value(tlv_values_t *values, byte type, int value);
tlv_t *tlv_get_value(const tlv_values_t *values, byte type);
int tlv_get_integer_value(const tlv_values_t *values, byte type, int def);
int tlv_format(const tlv_values_t *values, byte *buffer, size_t *size);
int tlv_parse(const byte *buffer, size_t length, tlv_values_t *values);
#endif // __TLV_H__
|
q-barbar/esp-homekit-devices | external_libs/wifi_config/src/form_urlencoded.c | #include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "form_urlencoded.h"
char *url_unescape(const char *buffer, size_t size) {
int len = 0;
int ishex(int c) {
c = toupper(c);
return ('0' <= c && c <= '9') || ('A' <= c && c <= 'F');
}
int hexvalue(int c) {
c = toupper(c);
if ('0' <= c && c <= '9')
return c - '0';
else
return c - 'A' + 10;
}
int i = 0, j;
while (i < size) {
len++;
if (buffer[i] == '%') {
i += 3;
} else {
i++;
}
}
char *result = malloc(len+1);
i = j = 0;
while (i < size) {
if (buffer[i] == '+') {
result[j++] = ' ';
i++;
} else if (buffer[i] != '%') {
result[j++] = buffer[i++];
} else {
if (i+2 < size && ishex(buffer[i+1]) && ishex(buffer[i+2])) {
result[j++] = hexvalue(buffer[i+1])*16 + hexvalue(buffer[i+2]);
i += 3;
} else {
result[j++] = buffer[i++];
}
}
}
result[j] = 0;
return result;
}
form_param_t *form_params_parse(const char *s) {
form_param_t *params = NULL;
int i = 0;
while (1) {
int pos = i;
while (s[i] && s[i] != '=' && s[i] != '&') i++;
if (i == pos) {
i++;
continue;
}
form_param_t *param = malloc(sizeof(form_param_t));
param->name = url_unescape(s+pos, i-pos);
param->value = NULL;
param->next = params;
params = param;
if (s[i] == '=') {
i++;
pos = i;
while (s[i] && s[i] != '&') i++;
if (i != pos) {
param->value = url_unescape(s+pos, i-pos);
}
}
if (!s[i])
break;
}
return params;
}
form_param_t *form_params_find(form_param_t *params, const char *name) {
while (params) {
if (!strcmp(params->name, name))
return params;
params = params->next;
}
return NULL;
}
void form_params_free(form_param_t *params) {
while (params) {
form_param_t *next = params->next;
if (params->name)
free(params->name);
if (params->value)
free(params->value);
free(params);
params = next;
}
}
|
q-barbar/esp-homekit-devices | external_libs/homekit/src/tlv.c | <gh_stars>1-10
#include <stdlib.h>
#include <string.h>
#include "tlv.h"
tlv_values_t *tlv_new() {
tlv_values_t *values = malloc(sizeof(tlv_values_t));
values->head = NULL;
return values;
}
void tlv_free(tlv_values_t *values) {
tlv_t *t = values->head;
while (t) {
tlv_t *t2 = t;
t = t->next;
if (t2->value)
free(t2->value);
free(t2);
}
free(values);
}
int tlv_add_value(tlv_values_t *values, byte type, const byte *value, size_t size) {
tlv_t *tlv = malloc(sizeof(tlv_t));
tlv->type = type;
tlv->size = size;
if (size) {
tlv->value = malloc(size);
} else {
tlv->value = NULL;
}
memcpy(tlv->value, value, size);
tlv->next = values->head;
values->head = tlv;
return 0;
}
int tlv_add_string_value(tlv_values_t *values, byte type, const char *value) {
return tlv_add_value(values, type, (const byte *)value, strlen(value));
}
int tlv_add_integer_value(tlv_values_t *values, byte type, int value) {
byte data[sizeof(value)];
size_t size = 1;
data[0] = value & 0xff;
value >>= 8;
while (value) {
data[size++] = value & 0xff;
value >>= 8;
}
return tlv_add_value(values, type, data, size);
}
tlv_t *tlv_get_value(const tlv_values_t *values, byte type) {
tlv_t *t = values->head;
while (t) {
if (t->type == type)
return t;
t = t->next;
}
return NULL;
}
int tlv_get_integer_value(const tlv_values_t *values, byte type, int def) {
tlv_t *t = tlv_get_value(values, type);
if (!t)
return 0;
int x = 0;
for (int i=t->size-1; i>=0; i--) {
x = (x << 8) + t->value[i];
}
return x;
}
int tlv_format(const tlv_values_t *values, byte *buffer, size_t *size) {
size_t required_size = 0;
tlv_t *t = values->head;
while (t) {
required_size += t->size + 2 * ((t->size + 254) / 255);
t = t->next;
}
if (*size < required_size) {
*size = required_size;
return -1;
}
*size = required_size;
t = values->head;
while (t) {
byte *data = t->value;
if (!t->size) {
buffer[0] = t->type;
buffer[1] = 0;
buffer += 2;
t = t->next;
continue;
}
size_t remaining = t->size;
while (remaining) {
buffer[0] = t->type;
size_t chunk_size = (remaining > 255) ? 255 : remaining;
buffer[1] = chunk_size;
memcpy(&buffer[2], data, chunk_size);
remaining -= chunk_size;
buffer += chunk_size + 2;
data += chunk_size;
}
t = t->next;
}
return 0;
}
int tlv_parse(const byte *buffer, size_t length, tlv_values_t *values) {
size_t i = 0;
while (i < length) {
tlv_t *t = malloc(sizeof(tlv_t));
t->type = buffer[i];
t->size = 0;
size_t j = i;
while (j < length && buffer[j] == t->type && buffer[j+1] == 255) {
size_t chunk_size = buffer[j+1];
t->size += chunk_size;
j += chunk_size + 2;
}
if (j < length && buffer[j] == t->type) {
t->size += buffer[j+1];
}
if (t->size == 0) {
t->value = NULL;
} else {
t->value = malloc(t->size);
byte *data = t->value;
size_t remaining = t->size;
while (remaining) {
size_t chunk_size = buffer[i+1];
memcpy(data, &buffer[i+2], chunk_size);
data += chunk_size;
i += chunk_size + 2;
remaining -= chunk_size;
}
}
t->next = values->head;
values->head = t;
}
return 0;
}
|
q-barbar/esp-homekit-devices | libs/led_codes/led_codes.h | /*
* LED Codes
*
* Copyright 2018 <NAME> (@RavenSystem)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
typedef struct blinking_params_t {
uint8_t times;
uint8_t duration;
} blinking_params_t;
#define GENERIC_ERROR (blinking_params_t){6,0}
#define SENSOR_ERROR (blinking_params_t){5,0}
#define WIFI_CONNECTED (blinking_params_t){1,2}
#define IDENTIFY_ACCESSORY (blinking_params_t){1,3}
#define RESTART_DEVICE (blinking_params_t){2,2}
#define WIFI_CONFIG_RESET (blinking_params_t){2,0}
#define EXTRA_CONFIG_RESET (blinking_params_t){2,1}
#define FUNCTION_A (blinking_params_t){1,0}
#define FUNCTION_B (blinking_params_t){2,0}
#define FUNCTION_C (blinking_params_t){3,0}
#define FUNCTION_D (blinking_params_t){4,0}
void led_code(uint8_t gpio, blinking_params_t blinking_params);
|
q-barbar/esp-homekit-devices | devices/RavenCore/main.c | /*
* RavenCore
*
* v0.5.4
*
* Copyright 2018 <NAME> (@RavenSystem)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Device Types
1. Switch Basic
2. Switch Dual
3. Socket + Button
4. Switch 4ch
5. Thermostat
6. Switch Basic + TH Sensor
7. Water Valve
8. Garage Door
9. Socket + Button + TH Sensor
10. ESP01 Switch + Button
11. Switch 3ch
*/
//#include <stdio.h>
//#include <string.h>
#include <esp/uart.h>
//#include <esp8266.h>
//#include <FreeRTOS.h>
//#include <espressif/esp_wifi.h>
//#include <espressif/esp_common.h>
#include <rboot-api.h>
#include <sysparam.h>
//#include <task.h>
//#include <etstimer.h>
#include <esplibs/libmain.h>
#include <homekit/homekit.h>
#include <homekit/characteristics.h>
#include <wifi_config.h>
#include <led_codes.h>
#include <adv_button.h>
#include <dht/dht.h>
#include <ds18b20/ds18b20.h>
#include "../common/custom_characteristics.h"
#define LED_GPIO 13
#define SENSOR_GPIO 14
#define DOOR_OPENED_GPIO 4
#define DOOR_CLOSED_GPIO 14
#define SONOFF_TOGGLE_GPIO 14
#define BUTTON1_GPIO 0
#define BUTTON2_GPIO 9
#define BUTTON3_GPIO 10
#define BUTTON4_GPIO 14
#define RELAY2_GPIO 5
#define RELAY3_GPIO 4
#define RELAY4_GPIO 15
#define DISABLED_TIME 60
bool gd_is_moving = false;
uint8_t device_type_static = 1, gd_time_state = 0, relay1_gpio = 12;
volatile uint32_t last_press_time;
volatile float old_humidity_value = 0.0, old_temperature_value = 0.0;
ETSTimer device_restart_timer, change_settings_timer, save_states_timer, extra_func_timer;
void switch1_on_callback(homekit_value_t value);
homekit_value_t read_switch1_on_callback();
void switch2_on_callback(homekit_value_t value);
homekit_value_t read_switch2_on_callback();
void switch3_on_callback(homekit_value_t value);
homekit_value_t read_switch3_on_callback();
void switch4_on_callback(homekit_value_t value);
homekit_value_t read_switch4_on_callback();
void on_target(homekit_value_t value);
homekit_value_t read_on_target();
void update_state();
void valve_on_callback(homekit_value_t value);
homekit_value_t read_valve_on_callback();
homekit_value_t read_in_use_on_callback();
homekit_value_t read_remaining_duration_on_callback();
void garage_on_callback(homekit_value_t value);
homekit_value_t read_garage_on_callback();
void show_setup_callback();
void ota_firmware_callback();
void gpio14_toggle_callback();
void change_settings_callback();
void save_states_callback();
void on_wifi_ready();
// ---------- CHARACTERISTICS ----------
// Switches
homekit_characteristic_t switch1_on = HOMEKIT_CHARACTERISTIC_(ON, false, .getter=read_switch1_on_callback, .setter=switch1_on_callback);
homekit_characteristic_t switch2_on = HOMEKIT_CHARACTERISTIC_(ON, false, .getter=read_switch2_on_callback, .setter=switch2_on_callback);
homekit_characteristic_t switch3_on = HOMEKIT_CHARACTERISTIC_(ON, false, .getter=read_switch3_on_callback, .setter=switch3_on_callback);
homekit_characteristic_t switch4_on = HOMEKIT_CHARACTERISTIC_(ON, false, .getter=read_switch4_on_callback, .setter=switch4_on_callback);
// For Outlets
homekit_characteristic_t switch_outlet_in_use = HOMEKIT_CHARACTERISTIC_(OUTLET_IN_USE, true); // It has not a real use, but it is a mandatory characteristic
// Stateless Button
homekit_characteristic_t button_event = HOMEKIT_CHARACTERISTIC_(PROGRAMMABLE_SWITCH_EVENT, 0);
// Thermostat
homekit_characteristic_t current_temperature = HOMEKIT_CHARACTERISTIC_(CURRENT_TEMPERATURE, 0);
homekit_characteristic_t target_temperature = HOMEKIT_CHARACTERISTIC_(TARGET_TEMPERATURE, 23, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(update_state));
homekit_characteristic_t units = HOMEKIT_CHARACTERISTIC_(TEMPERATURE_DISPLAY_UNITS, 0);
homekit_characteristic_t current_state = HOMEKIT_CHARACTERISTIC_(CURRENT_HEATING_COOLING_STATE, 0);
homekit_characteristic_t target_state = HOMEKIT_CHARACTERISTIC_(TARGET_HEATING_COOLING_STATE, 0, .getter=read_on_target, .setter=on_target);
homekit_characteristic_t current_humidity = HOMEKIT_CHARACTERISTIC_(CURRENT_RELATIVE_HUMIDITY, 0);
// Water Valve
homekit_characteristic_t active = HOMEKIT_CHARACTERISTIC_(ACTIVE, 0, .getter=read_valve_on_callback, .setter=valve_on_callback);
homekit_characteristic_t in_use = HOMEKIT_CHARACTERISTIC_(IN_USE, 0, .getter=read_in_use_on_callback);
homekit_characteristic_t valve_type = HOMEKIT_CHARACTERISTIC_(VALVE_TYPE, 0);
homekit_characteristic_t set_duration = HOMEKIT_CHARACTERISTIC_(SET_DURATION, 900, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(save_states_callback));
homekit_characteristic_t remaining_duration = HOMEKIT_CHARACTERISTIC_(REMAINING_DURATION, 0, .getter=read_remaining_duration_on_callback);
// Garage Door
homekit_characteristic_t current_door_state = HOMEKIT_CHARACTERISTIC_(CURRENT_DOOR_STATE, 1);
homekit_characteristic_t target_door_state = HOMEKIT_CHARACTERISTIC_(TARGET_DOOR_STATE, 1, .getter=read_garage_on_callback, .setter=garage_on_callback);
homekit_characteristic_t obstruction_detected = HOMEKIT_CHARACTERISTIC_(OBSTRUCTION_DETECTED, false);
// ---------- SETUP ----------
// General Setup
homekit_characteristic_t show_setup = HOMEKIT_CHARACTERISTIC_(CUSTOM_SHOW_SETUP, false, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(show_setup_callback));
homekit_characteristic_t device_type = HOMEKIT_CHARACTERISTIC_(CUSTOM_DEVICE_TYPE, 1, .id=102, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t reboot_device = HOMEKIT_CHARACTERISTIC_(CUSTOM_REBOOT_DEVICE, false, .id=103, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(ota_firmware_callback));
homekit_characteristic_t ota_firmware = HOMEKIT_CHARACTERISTIC_(CUSTOM_OTA_UPDATE, false, .id=110, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(ota_firmware_callback));
// Switch 1 Setup
homekit_characteristic_t gpio14_toggle = HOMEKIT_CHARACTERISTIC_(CUSTOM_GPIO14_TOGGLE, false, .id=111, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(gpio14_toggle_callback));
// Thermostat Setup
homekit_characteristic_t dht_sensor_type = HOMEKIT_CHARACTERISTIC_(CUSTOM_DHT_SENSOR_TYPE, 2, .id=112, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t poll_period = HOMEKIT_CHARACTERISTIC_(CUSTOM_TH_PERIOD, 30, .id=125, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(save_states_callback));
// Water Valve Setup
homekit_characteristic_t custom_valve_type = HOMEKIT_CHARACTERISTIC_(CUSTOM_VALVE_TYPE, 0, .id=113, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
// Garage Door Setup
homekit_characteristic_t custom_garagedoor_has_stop = HOMEKIT_CHARACTERISTIC_(CUSTOM_GARAGEDOOR_HAS_STOP, false, .id=114, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t custom_garagedoor_sensor_close_nc = HOMEKIT_CHARACTERISTIC_(CUSTOM_GARAGEDOOR_SENSOR_CLOSE_NC, false, .id=115, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t custom_garagedoor_sensor_open_nc = HOMEKIT_CHARACTERISTIC_(CUSTOM_GARAGEDOOR_SENSOR_OPEN_NC, false, .id=116, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t custom_garagedoor_has_sensor_open = HOMEKIT_CHARACTERISTIC_(CUSTOM_GARAGEDOOR_HAS_SENSOR_OPEN, false, .id=117, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t custom_garagedoor_working_time = HOMEKIT_CHARACTERISTIC_(CUSTOM_GARAGEDOOR_WORKINGTIME, 20, .id=118, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t custom_garagedoor_control_with_button = HOMEKIT_CHARACTERISTIC_(CUSTOM_GARAGEDOOR_CONTROL_WITH_BUTTON, false, .id=119, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
// Initial State Setup
homekit_characteristic_t custom_init_state_sw1 = HOMEKIT_CHARACTERISTIC_(CUSTOM_INIT_STATE_SW1, 0, .id=120, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t custom_init_state_sw2 = HOMEKIT_CHARACTERISTIC_(CUSTOM_INIT_STATE_SW2, 0, .id=121, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t custom_init_state_sw3 = HOMEKIT_CHARACTERISTIC_(CUSTOM_INIT_STATE_SW3, 0, .id=122, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t custom_init_state_sw4 = HOMEKIT_CHARACTERISTIC_(CUSTOM_INIT_STATE_SW4, 0, .id=123, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
homekit_characteristic_t custom_init_state_th = HOMEKIT_CHARACTERISTIC_(CUSTOM_INIT_STATE_TH, 0, .id=124, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(change_settings_callback));
// Last used ID = 125
// ---------------------------
void relay_write(bool on, int gpio) {
last_press_time = xTaskGetTickCountFromISR() + (DISABLED_TIME / portTICK_PERIOD_MS);
adv_button_set_disable_time();
gpio_write(gpio, on ? 1 : 0);
}
void led_write(bool on) {
gpio_write(LED_GPIO, on ? 0 : 1);
}
void on_target(homekit_value_t value) {
target_state.value = value;
switch (target_state.value.int_value) {
case 1:
printf("RC >>> Set to HEAT\n");
led_code(LED_GPIO, FUNCTION_B);
break;
case 2:
printf("RC >>> Set to COOL\n");
led_code(LED_GPIO, FUNCTION_C);
break;
default:
printf("RC >>> Set to OFF\n");
led_code(LED_GPIO, FUNCTION_A);
break;
}
update_state();
}
homekit_value_t read_on_target() {
return target_state.value;
}
void update_state() {
uint8_t state = target_state.value.int_value;
if (state == 3) {
state = 0;
target_state.value = HOMEKIT_UINT8(0);
homekit_characteristic_notify(&target_state, target_state.value);
}
if (state == 1 && current_temperature.value.float_value < target_temperature.value.float_value) {
if (current_state.value.int_value != 1) {
current_state.value = HOMEKIT_UINT8(1);
homekit_characteristic_notify(¤t_state, current_state.value);
relay_write(true, relay1_gpio);
}
} else if (state == 2 && current_temperature.value.float_value > target_temperature.value.float_value) {
if (current_state.value.int_value != 2) {
current_state.value = HOMEKIT_UINT8(2);
homekit_characteristic_notify(¤t_state, current_state.value);
relay_write(true, relay1_gpio);
}
} else if (current_state.value.int_value != 0) {
current_state.value = HOMEKIT_UINT8(0);
homekit_characteristic_notify(¤t_state, current_state.value);
relay_write(false, relay1_gpio);
}
save_states_callback();
}
void save_settings() {
printf("RC >>> Saving settings\n");
sysparam_status_t status;
bool bool_value;
int8_t int8_value;
status = sysparam_get_bool("show_setup", &bool_value);
if (status == SYSPARAM_OK && bool_value != show_setup.value.bool_value) {
sysparam_set_bool("show_setup", show_setup.value.bool_value);
}
status = sysparam_get_int8("device_type", &int8_value);
if (status == SYSPARAM_OK && int8_value != device_type.value.int_value) {
sysparam_set_int8("device_type", device_type.value.int_value);
}
status = sysparam_get_bool("gpio14_toggle", &bool_value);
if (status == SYSPARAM_OK && bool_value != gpio14_toggle.value.bool_value) {
sysparam_set_bool("gpio14_toggle", gpio14_toggle.value.bool_value);
}
status = sysparam_get_int8("dht_sensor_type", &int8_value);
if (status == SYSPARAM_OK && int8_value != dht_sensor_type.value.int_value) {
sysparam_set_int8("dht_sensor_type", dht_sensor_type.value.int_value);
}
status = sysparam_get_int8("poll_period", &int8_value);
if (status == SYSPARAM_OK && int8_value != poll_period.value.int_value) {
sysparam_set_int8("poll_period", poll_period.value.int_value);
}
status = sysparam_get_int8("valve_type", &int8_value);
if (status == SYSPARAM_OK && int8_value != custom_valve_type.value.int_value) {
sysparam_set_int8("valve_type", custom_valve_type.value.int_value);
valve_type.value.int_value = int8_value;
homekit_characteristic_notify(&valve_type, valve_type.value);
}
status = sysparam_get_int8("garagedoor_working_time", &int8_value);
if (status == SYSPARAM_OK && int8_value != custom_garagedoor_working_time.value.int_value) {
sysparam_set_int8("garagedoor_working_time", custom_garagedoor_working_time.value.int_value);
}
status = sysparam_get_bool("garagedoor_has_stop", &bool_value);
if (status == SYSPARAM_OK && bool_value != custom_garagedoor_has_stop.value.bool_value) {
sysparam_set_bool("garagedoor_has_stop", custom_garagedoor_has_stop.value.bool_value);
}
status = sysparam_get_bool("garagedoor_sensor_close_nc", &bool_value);
if (status == SYSPARAM_OK && bool_value != custom_garagedoor_sensor_close_nc.value.bool_value) {
sysparam_set_bool("garagedoor_sensor_close_nc", custom_garagedoor_sensor_close_nc.value.bool_value);
}
status = sysparam_get_bool("garagedoor_sensor_open_nc", &bool_value);
if (status == SYSPARAM_OK && bool_value != custom_garagedoor_sensor_open_nc.value.bool_value) {
sysparam_set_bool("garagedoor_sensor_open_nc", custom_garagedoor_sensor_open_nc.value.bool_value);
}
status = sysparam_get_bool("garagedoor_has_sensor_open", &bool_value);
if (status == SYSPARAM_OK && bool_value != custom_garagedoor_has_sensor_open.value.bool_value) {
sysparam_set_bool("garagedoor_has_sensor_open", custom_garagedoor_has_sensor_open.value.bool_value);
}
status = sysparam_get_bool("garagedoor_control_with_button", &bool_value);
if (status == SYSPARAM_OK && bool_value != custom_garagedoor_control_with_button.value.bool_value) {
sysparam_set_bool("garagedoor_control_with_button", custom_garagedoor_control_with_button.value.bool_value);
}
status = sysparam_get_int8("init_state_sw1", &int8_value);
if (status == SYSPARAM_OK && int8_value != custom_init_state_sw1.value.int_value) {
sysparam_set_int8("init_state_sw1", custom_init_state_sw1.value.int_value);
}
status = sysparam_get_int8("init_state_sw2", &int8_value);
if (status == SYSPARAM_OK && int8_value != custom_init_state_sw2.value.int_value) {
sysparam_set_int8("init_state_sw2", custom_init_state_sw2.value.int_value);
}
status = sysparam_get_int8("init_state_sw3", &int8_value);
if (status == SYSPARAM_OK && int8_value != custom_init_state_sw3.value.int_value) {
sysparam_set_int8("init_state_sw3", custom_init_state_sw3.value.int_value);
}
status = sysparam_get_int8("init_state_sw4", &int8_value);
if (status == SYSPARAM_OK && int8_value != custom_init_state_sw4.value.int_value) {
sysparam_set_int8("init_state_sw4", custom_init_state_sw4.value.int_value);
}
status = sysparam_get_int8("init_state_th", &int8_value);
if (status == SYSPARAM_OK && int8_value != custom_init_state_th.value.int_value) {
sysparam_set_int8("init_state_th", custom_init_state_th.value.int_value);
}
}
void save_states() {
printf("RC >>> Saving last states\n");
sysparam_status_t status;
bool bool_value;
int8_t int8_value;
int32_t int32_value;
if (custom_init_state_sw1.value.int_value > 1) {
status = sysparam_get_bool("last_state_sw1", &bool_value);
if (status == SYSPARAM_OK && bool_value != switch1_on.value.bool_value) {
sysparam_set_bool("last_state_sw1", switch1_on.value.bool_value);
}
}
if (custom_init_state_sw2.value.int_value > 1) {
status = sysparam_get_bool("last_state_sw2", &bool_value);
if (status == SYSPARAM_OK && bool_value != switch2_on.value.bool_value) {
sysparam_set_bool("last_state_sw2", switch2_on.value.bool_value);
}
}
if (custom_init_state_sw3.value.int_value > 1) {
status = sysparam_get_bool("last_state_sw3", &bool_value);
if (status == SYSPARAM_OK && bool_value != switch3_on.value.bool_value) {
sysparam_set_bool("last_state_sw3", switch3_on.value.bool_value);
}
}
if (custom_init_state_sw4.value.int_value > 1) {
status = sysparam_get_bool("last_state_sw4", &bool_value);
if (status == SYSPARAM_OK && bool_value != switch4_on.value.bool_value) {
sysparam_set_bool("last_state_sw4", switch4_on.value.bool_value);
}
}
if (custom_init_state_th.value.int_value > 2) {
status = sysparam_get_int8("last_target_state_th", &int8_value);
if (status == SYSPARAM_OK && int8_value != target_state.value.int_value) {
sysparam_set_int8("last_target_state_th", target_state.value.int_value);
}
}
status = sysparam_get_int32("target_temp", &int32_value);
int32_t target_temp = target_temperature.value.float_value * 100;
if (status == SYSPARAM_OK && int32_value != target_temp) {
sysparam_set_int32("target_temp", target_temp);
}
status = sysparam_get_int32("set_duration", &int32_value);
if (status == SYSPARAM_OK && int32_value != set_duration.value.int_value) {
sysparam_set_int32("set_duration", set_duration.value.int_value);
}
}
void device_restart_task() {
vTaskDelay(5500 / portTICK_PERIOD_MS);
if (ota_firmware.value.bool_value) {
rboot_set_temp_rom(1);
vTaskDelay(100 / portTICK_PERIOD_MS);
}
sdk_system_restart();
vTaskDelete(NULL);
}
void device_restart() {
printf("RC >>> Restarting device\n");
led_code(LED_GPIO, RESTART_DEVICE);
xTaskCreate(device_restart_task, "device_restart_task", 256, NULL, 1, NULL);
}
void show_setup_callback() {
if (show_setup.value.bool_value) {
sdk_os_timer_setfn(&device_restart_timer, device_restart, NULL);
sdk_os_timer_arm(&device_restart_timer, 5000, 0);
} else {
sdk_os_timer_disarm(&device_restart_timer);
}
save_settings();
}
void reset_call_task() {
printf("RC >>> Resetting device to factory defaults\n");
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("show_setup", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("device_type", 1);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("gpio14_toggle", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("dht_sensor_type", 2);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("poll_period", 30);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("valve_type", 0);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("garagedoor_working_time", 20);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("garagedoor_has_stop", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("garagedoor_sensor_close_nc", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("garagedoor_sensor_open_nc", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("garagedoor_has_sensor_open", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("garagedoor_control_with_button", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int32("target_temp", 2300);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int32("set_duration", 900);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("init_state_sw1", 0);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("init_state_sw2", 0);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("init_state_sw3", 0);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("init_state_sw4", 0);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("init_state_th", 0);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("last_state_sw1", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("last_state_sw2", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("last_state_sw3", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_bool("last_state_sw4", false);
vTaskDelay(50 / portTICK_PERIOD_MS);
sysparam_set_int8("last_target_state_th", 0);
vTaskDelay(50 / portTICK_PERIOD_MS);
homekit_server_reset();
vTaskDelay(500 / portTICK_PERIOD_MS);
wifi_config_reset();
vTaskDelay(500 / portTICK_PERIOD_MS);
led_code(LED_GPIO, EXTRA_CONFIG_RESET);
vTaskDelay(2200 / portTICK_PERIOD_MS);
sdk_system_restart();
vTaskDelete(NULL);
}
void reset_call(const uint8_t gpio) {
led_code(LED_GPIO, WIFI_CONFIG_RESET);
relay_write(false, relay1_gpio);
gpio_disable(relay1_gpio);
xTaskCreate(reset_call_task, "reset_call_task", 256, NULL, 1, NULL);
}
void ota_firmware_callback() {
if (ota_firmware.value.bool_value || reboot_device.value.bool_value) {
sdk_os_timer_setfn(&device_restart_timer, device_restart, NULL);
sdk_os_timer_arm(&device_restart_timer, 5000, 0);
} else {
sdk_os_timer_disarm(&device_restart_timer);
}
}
void change_settings_callback() {
sdk_os_timer_disarm(&change_settings_timer);
sdk_os_timer_arm(&change_settings_timer, 3000, 0);
}
void save_states_callback() {
sdk_os_timer_disarm(&save_states_timer);
sdk_os_timer_arm(&save_states_timer, 3000, 0);
}
void switch1_on_callback(homekit_value_t value) {
printf("RC >>> Toggle Switch 1\n");
led_code(LED_GPIO, FUNCTION_A);
switch1_on.value = value;
relay_write(switch1_on.value.bool_value, relay1_gpio);
printf("RC >>> Relay 1 -> %i\n", switch1_on.value.bool_value);
save_states_callback();
}
homekit_value_t read_switch1_on_callback() {
return switch1_on.value;
}
void switch2_on_callback(homekit_value_t value) {
printf("RC >>> Toggle Switch 2\n");
led_code(LED_GPIO, FUNCTION_A);
switch2_on.value = value;
relay_write(switch2_on.value.bool_value, RELAY2_GPIO);
printf("RC >>> Relay 2 -> %i\n", switch2_on.value.bool_value);
save_states_callback();
}
homekit_value_t read_switch2_on_callback() {
return switch2_on.value;
}
void switch3_on_callback(homekit_value_t value) {
printf("RC >>> Toggle Switch 3\n");
led_code(LED_GPIO, FUNCTION_A);
switch3_on.value = value;
relay_write(switch3_on.value.bool_value, RELAY3_GPIO);
printf("RC >>> Relay 3 -> %i\n", switch3_on.value.bool_value);
save_states_callback();
}
homekit_value_t read_switch3_on_callback() {
return switch3_on.value;
}
void switch4_on_callback(homekit_value_t value) {
printf("RC >>> Toggle Switch 4\n");
led_code(LED_GPIO, FUNCTION_A);
switch4_on.value = value;
relay_write(switch4_on.value.bool_value, RELAY4_GPIO);
printf("RC >>> Relay 4 -> %i\n", switch4_on.value.bool_value);
save_states_callback();
}
homekit_value_t read_switch4_on_callback() {
return switch4_on.value;
}
void toggle_switch(const uint8_t gpio) {
printf("RC >>> Toggle Switch manual\n");
led_code(LED_GPIO, FUNCTION_A);
switch1_on.value.bool_value = !switch1_on.value.bool_value;
relay_write(switch1_on.value.bool_value, relay1_gpio);
printf("RC >>> Relay 1 -> %i\n", switch1_on.value.bool_value);
homekit_characteristic_notify(&switch1_on, switch1_on.value);
save_states_callback();
}
void gpio14_toggle_callback() {
if (gpio14_toggle.value.bool_value) {
adv_toggle_create(SONOFF_TOGGLE_GPIO);
adv_toggle_register_callback_fn(SONOFF_TOGGLE_GPIO, toggle_switch, 2);
} else {
adv_toggle_destroy(SONOFF_TOGGLE_GPIO);
}
change_settings_callback();
}
void toggle_valve() {
if (active.value.int_value == 1) {
active.value.int_value = 0;
} else {
active.value.int_value = 1;
}
homekit_characteristic_notify(&active, active.value);
valve_on_callback(active.value);
}
void valve_control() {
remaining_duration.value.int_value--;
if (remaining_duration.value.int_value == 0) {
printf("RC >>> Valve OFF\n");
led_code(LED_GPIO, FUNCTION_D);
sdk_os_timer_disarm(&extra_func_timer);
relay_write(false, relay1_gpio);
active.value.int_value = 0;
in_use.value.int_value = 0;
homekit_characteristic_notify(&active, active.value);
homekit_characteristic_notify(&in_use, in_use.value);
}
}
void valve_on_callback(homekit_value_t value) {
led_code(LED_GPIO, FUNCTION_A);
active.value = value;
in_use.value.int_value = active.value.int_value;
if (active.value.int_value == 1) {
printf("RC >>> Valve ON\n");
relay_write(true, relay1_gpio);
remaining_duration.value = set_duration.value;
sdk_os_timer_arm(&extra_func_timer, 1000, 1);
} else {
printf("RC >>> Valve manual OFF\n");
sdk_os_timer_disarm(&extra_func_timer);
relay_write(false, relay1_gpio);
remaining_duration.value.int_value = 0;
}
homekit_characteristic_notify(&in_use, in_use.value);
homekit_characteristic_notify(&remaining_duration, remaining_duration.value);
}
homekit_value_t read_valve_on_callback() {
return active.value;
}
homekit_value_t read_in_use_on_callback() {
return in_use.value;
}
homekit_value_t read_remaining_duration_on_callback() {
return remaining_duration.value;
}
void garage_button_task() {
printf("RC >>> Garage Door relay working\n");
if (!custom_garagedoor_has_sensor_open.value.bool_value) {
sdk_os_timer_disarm(&extra_func_timer);
}
relay_write(true, relay1_gpio);
vTaskDelay(250 / portTICK_PERIOD_MS);
relay_write(false, relay1_gpio);
if (custom_garagedoor_has_stop.value.bool_value && gd_is_moving) {
vTaskDelay(2000 / portTICK_PERIOD_MS);
relay_write(true, relay1_gpio);
vTaskDelay(250 / portTICK_PERIOD_MS);
relay_write(false, relay1_gpio);
}
if (!custom_garagedoor_has_sensor_open.value.bool_value) {
if (current_door_state.value.int_value == 0 || current_door_state.value.int_value == 2) {
printf("RC >>> Garage Door -> CLOSING\n");
current_door_state.value.int_value = 3;
sdk_os_timer_arm(&extra_func_timer, 1000, 1);
} else if (current_door_state.value.int_value == 3) {
printf("RC >>> Garage Door -> OPENING\n");
current_door_state.value.int_value = 2;
sdk_os_timer_arm(&extra_func_timer, 1000, 1);
}
}
homekit_characteristic_notify(¤t_door_state, current_door_state.value);
vTaskDelete(NULL);
}
void garage_on_callback(homekit_value_t value) {
printf("RC >>> Garage Door activated: Current state -> %i, Target state -> %i\n", current_door_state.value.int_value, value.int_value);
uint8_t current_door_state_simple = current_door_state.value.int_value;
if (current_door_state_simple > 1) {
current_door_state_simple -= 2;
}
if (value.int_value != current_door_state_simple) {
led_code(LED_GPIO, FUNCTION_A);
xTaskCreate(garage_button_task, "garage_button_task", 192, NULL, 1, NULL);
} else {
led_code(LED_GPIO, FUNCTION_D);
}
target_door_state.value = value;
}
void garage_on_button(const uint8_t gpio) {
if (custom_garagedoor_control_with_button.value.bool_value) {
printf("RC >>> Garage Door: built-in button PRESSED\n");
if (target_door_state.value.int_value == 0) {
garage_on_callback(HOMEKIT_UINT8(1));
} else {
garage_on_callback(HOMEKIT_UINT8(0));
}
} else {
printf("RC >>> Garage Door: built-in button DISABLED\n");
led_code(LED_GPIO, FUNCTION_D);
}
}
homekit_value_t read_garage_on_callback() {
printf("RC >>> Garage Door: returning target_door_state -> %i\n", target_door_state.value.int_value);
return target_door_state.value;
}
static void homekit_gd_notify() {
homekit_characteristic_notify(&target_door_state, target_door_state.value);
homekit_characteristic_notify(¤t_door_state, current_door_state.value);
}
void door_opened_0_fn_callback(const uint8_t gpio) {
printf("RC >>> Garage Door -> CLOSING\n");
gd_is_moving = true;
target_door_state.value.int_value = 1;
current_door_state.value.int_value = 3;
homekit_gd_notify();
}
void door_opened_1_fn_callback(const uint8_t gpio) {
printf("RC >>> Garage Door -> OPENED\n");
gd_is_moving = false;
target_door_state.value.int_value = 0;
current_door_state.value.int_value = 0;
homekit_gd_notify();
}
void door_closed_0_fn_callback(const uint8_t gpio) {
printf("RC >>> Garage Door -> OPENING\n");
gd_is_moving = true;
target_door_state.value.int_value = 0;
current_door_state.value.int_value = 2;
if (!custom_garagedoor_has_sensor_open.value.bool_value) {
sdk_os_timer_arm(&extra_func_timer, 1000, 1);
}
homekit_gd_notify();
}
void door_closed_1_fn_callback(const uint8_t gpio) {
printf("RC >>> Garage Door -> CLOSED\n");
gd_time_state = 0;
gd_is_moving = false;
target_door_state.value.int_value = 1;
current_door_state.value.int_value = 1;
if (!custom_garagedoor_has_sensor_open.value.bool_value) {
sdk_os_timer_disarm(&extra_func_timer);
}
homekit_gd_notify();
}
void door_opened_countdown_timer() {
if (gd_time_state > custom_garagedoor_working_time.value.int_value) {
gd_time_state = custom_garagedoor_working_time.value.int_value - 1;
}
if (current_door_state.value.int_value == 2) {
gd_time_state++;
if (gd_time_state == custom_garagedoor_working_time.value.int_value) {
printf("RC >>> Garage Door -> OPENED\n");
sdk_os_timer_disarm(&extra_func_timer);
gd_is_moving = false;
gd_time_state = custom_garagedoor_working_time.value.int_value;
target_door_state.value.int_value = 0;
current_door_state.value.int_value = 0;
homekit_gd_notify();
}
} else if (current_door_state.value.int_value == 3) {
gd_time_state--;
if (gd_time_state == 0) {
printf("RC >>> Garage Door -> CLOSED\n");
sdk_os_timer_disarm(&extra_func_timer);
gd_is_moving = false;
target_door_state.value.int_value = 1;
current_door_state.value.int_value = 1;
homekit_gd_notify();
}
}
}
void button_simple1_intr_callback(const uint8_t gpio) {
if (device_type_static == 7) {
toggle_valve();
} else {
toggle_switch(gpio);
}
}
void button_simple2_intr_callback(const uint8_t gpio) {
switch2_on.value.bool_value = !switch2_on.value.bool_value;
switch2_on_callback(switch2_on.value);
homekit_characteristic_notify(&switch2_on, switch2_on.value);
}
void button_simple3_intr_callback(const uint8_t gpio) {
switch3_on.value.bool_value = !switch3_on.value.bool_value;
switch3_on_callback(switch3_on.value);
homekit_characteristic_notify(&switch3_on, switch3_on.value);
}
void button_simple4_intr_callback(const uint8_t gpio) {
switch4_on.value.bool_value = !switch4_on.value.bool_value;
switch4_on_callback(switch4_on.value);
homekit_characteristic_notify(&switch4_on, switch4_on.value);
}
void button_event1_intr_callback(const uint8_t gpio) {
led_code(LED_GPIO, FUNCTION_A);
homekit_characteristic_notify(&button_event, HOMEKIT_UINT8(0));
}
void button_event2_intr_callback(const uint8_t gpio) {
led_code(LED_GPIO, FUNCTION_B);
homekit_characteristic_notify(&button_event, HOMEKIT_UINT8(1));
}
void button_event3_intr_callback(const uint8_t gpio) {
led_code(LED_GPIO, FUNCTION_C);
homekit_characteristic_notify(&button_event, HOMEKIT_UINT8(2));
}
void th_button_intr_callback(const uint8_t gpio) {
uint8_t state = target_state.value.int_value + 1;
switch (state) {
case 1:
printf("RC >>> Thermostat set to HEAT\n");
led_code(LED_GPIO, FUNCTION_B);
break;
case 2:
printf("RC >>> Thermostat set to COOL\n");
led_code(LED_GPIO, FUNCTION_C);
break;
default:
state = 0;
printf("RC >>> Thermostat set to OFF\n");
led_code(LED_GPIO, FUNCTION_A);
break;
}
target_state.value = HOMEKIT_UINT8(state);
homekit_characteristic_notify(&target_state, target_state.value);
update_state();
}
void temperature_sensor_worker() {
float humidity_value, temperature_value;
bool get_temp = false;
if (dht_sensor_type.value.int_value < 3) {
dht_sensor_type_t current_sensor_type = DHT_TYPE_DHT22;
if (dht_sensor_type.value.int_value == 1) {
current_sensor_type = DHT_TYPE_DHT11;
}
get_temp = dht_read_float_data(current_sensor_type, SENSOR_GPIO, &humidity_value, &temperature_value);
} else { // dht_sensor_type.value.int_value == 3
ds18b20_addr_t ds18b20_addr[1];
if (ds18b20_scan_devices(SENSOR_GPIO, ds18b20_addr, 1) == 1) {
temperature_value = ds18b20_read_single(SENSOR_GPIO);
humidity_value = 0.0;
get_temp = true;
}
}
if (get_temp) {
printf("RC >>> Sensor: temperature %g, humidity %g\n", temperature_value, humidity_value);
if (temperature_value != old_temperature_value) {
old_temperature_value = temperature_value;
current_temperature.value = HOMEKIT_FLOAT(temperature_value);
homekit_characteristic_notify(¤t_temperature, current_temperature.value);
if (humidity_value != old_humidity_value) {
old_humidity_value = humidity_value;
current_humidity.value = HOMEKIT_FLOAT(humidity_value);
homekit_characteristic_notify(¤t_humidity, current_humidity.value);
}
if (device_type_static == 5) {
update_state();
}
}
} else {
printf("RC >>> Sensor: ERROR\n");
led_code(LED_GPIO, SENSOR_ERROR);
if (current_state.value.int_value != 0 && device_type_static == 5) {
current_state.value = HOMEKIT_UINT8(0);
homekit_characteristic_notify(¤t_state, current_state.value);
relay_write(false, relay1_gpio);
}
}
}
void identify(homekit_value_t _value) {
led_code(LED_GPIO, IDENTIFY_ACCESSORY);
}
void hardware_init() {
printf("RC >>> Initializing hardware...\n");
gpio_enable(LED_GPIO, GPIO_OUTPUT);
led_write(false);
adv_button_create(BUTTON1_GPIO);
switch (device_type_static) {
case 1:
adv_button_register_callback_fn(BUTTON1_GPIO, button_simple1_intr_callback, 1);
adv_button_register_callback_fn(BUTTON1_GPIO, reset_call, 5);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(switch1_on.value.bool_value, relay1_gpio);
gpio14_toggle_callback();
break;
case 2:
adv_button_create(BUTTON2_GPIO);
adv_button_create(BUTTON3_GPIO);
adv_button_register_callback_fn(BUTTON1_GPIO, button_simple1_intr_callback, 1);
adv_button_register_callback_fn(BUTTON2_GPIO, button_simple2_intr_callback, 1);
adv_button_register_callback_fn(BUTTON3_GPIO, button_simple1_intr_callback, 1);
adv_button_register_callback_fn(BUTTON3_GPIO, button_simple2_intr_callback, 2);
adv_button_register_callback_fn(BUTTON3_GPIO, reset_call, 5);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(switch1_on.value.bool_value, relay1_gpio);
gpio_enable(RELAY2_GPIO, GPIO_OUTPUT);
relay_write(switch2_on.value.bool_value, RELAY2_GPIO);
break;
case 3:
adv_button_register_callback_fn(BUTTON1_GPIO, button_event1_intr_callback, 1);
adv_button_register_callback_fn(BUTTON1_GPIO, button_event2_intr_callback, 2);
adv_button_register_callback_fn(BUTTON1_GPIO, button_event3_intr_callback, 3);
adv_button_register_callback_fn(BUTTON1_GPIO, button_simple1_intr_callback, 4);
adv_button_register_callback_fn(BUTTON1_GPIO, reset_call, 5);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(switch1_on.value.bool_value, relay1_gpio);
break;
case 4:
adv_button_create(BUTTON2_GPIO);
adv_button_create(BUTTON3_GPIO);
adv_button_create(BUTTON4_GPIO);
adv_button_register_callback_fn(BUTTON1_GPIO, button_simple1_intr_callback, 1);
adv_button_register_callback_fn(BUTTON1_GPIO, reset_call, 5);
adv_button_register_callback_fn(BUTTON2_GPIO, button_simple2_intr_callback, 1);
adv_button_register_callback_fn(BUTTON3_GPIO, button_simple3_intr_callback, 1);
adv_button_register_callback_fn(BUTTON4_GPIO, button_simple4_intr_callback, 1);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(switch1_on.value.bool_value, relay1_gpio);
gpio_enable(RELAY2_GPIO, GPIO_OUTPUT);
relay_write(switch2_on.value.bool_value, RELAY2_GPIO);
gpio_enable(RELAY3_GPIO, GPIO_OUTPUT);
relay_write(switch3_on.value.bool_value, RELAY3_GPIO);
gpio_enable(RELAY4_GPIO, GPIO_OUTPUT);
relay_write(switch4_on.value.bool_value, RELAY4_GPIO);
break;
case 5:
adv_button_register_callback_fn(BUTTON1_GPIO, th_button_intr_callback, 1);
adv_button_register_callback_fn(BUTTON1_GPIO, reset_call, 5);
gpio_set_pullup(SENSOR_GPIO, false, false);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(false, relay1_gpio);
sdk_os_timer_setfn(&extra_func_timer, temperature_sensor_worker, NULL);
sdk_os_timer_arm(&extra_func_timer, poll_period.value.int_value * 1000, 1);
break;
case 6:
adv_button_register_callback_fn(BUTTON1_GPIO, button_simple1_intr_callback, 1);
adv_button_register_callback_fn(BUTTON1_GPIO, reset_call, 5);
gpio_set_pullup(SENSOR_GPIO, false, false);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(switch1_on.value.bool_value, relay1_gpio);
sdk_os_timer_setfn(&extra_func_timer, temperature_sensor_worker, NULL);
sdk_os_timer_arm(&extra_func_timer, poll_period.value.int_value * 1000, 1);
break;
case 7:
adv_button_register_callback_fn(BUTTON1_GPIO, button_simple1_intr_callback, 1);
adv_button_register_callback_fn(BUTTON1_GPIO, reset_call, 5);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(false, relay1_gpio);
sdk_os_timer_setfn(&extra_func_timer, valve_control, NULL);
break;
case 8:
adv_button_register_callback_fn(BUTTON1_GPIO, garage_on_button, 1);
adv_button_register_callback_fn(BUTTON1_GPIO, reset_call, 5);
adv_toggle_create(DOOR_CLOSED_GPIO);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(false, relay1_gpio);
if (custom_garagedoor_sensor_close_nc.value.bool_value) {
adv_toggle_register_callback_fn(DOOR_CLOSED_GPIO, door_closed_1_fn_callback, 0);
adv_toggle_register_callback_fn(DOOR_CLOSED_GPIO, door_closed_0_fn_callback, 1);
} else {
adv_toggle_register_callback_fn(DOOR_CLOSED_GPIO, door_closed_0_fn_callback, 0);
adv_toggle_register_callback_fn(DOOR_CLOSED_GPIO, door_closed_1_fn_callback, 1);
}
if (custom_garagedoor_has_sensor_open.value.bool_value) {
adv_toggle_create(DOOR_OPENED_GPIO);
if (custom_garagedoor_sensor_open_nc.value.bool_value) {
adv_toggle_register_callback_fn(DOOR_OPENED_GPIO, door_opened_1_fn_callback, 0);
adv_toggle_register_callback_fn(DOOR_OPENED_GPIO, door_opened_0_fn_callback, 1);
} else {
adv_toggle_register_callback_fn(DOOR_OPENED_GPIO, door_opened_0_fn_callback, 0);
adv_toggle_register_callback_fn(DOOR_OPENED_GPIO, door_opened_1_fn_callback, 1);
}
} else {
sdk_os_timer_setfn(&extra_func_timer, door_opened_countdown_timer, NULL);
}
break;
case 9:
adv_button_register_callback_fn(BUTTON1_GPIO, button_event1_intr_callback, 1);
adv_button_register_callback_fn(BUTTON1_GPIO, button_event2_intr_callback, 2);
adv_button_register_callback_fn(BUTTON1_GPIO, button_event3_intr_callback, 3);
adv_button_register_callback_fn(BUTTON1_GPIO, button_simple1_intr_callback, 4);
adv_button_register_callback_fn(BUTTON1_GPIO, reset_call, 5);
gpio_set_pullup(SENSOR_GPIO, false, false);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(switch1_on.value.bool_value, relay1_gpio);
sdk_os_timer_setfn(&extra_func_timer, temperature_sensor_worker, NULL);
sdk_os_timer_arm(&extra_func_timer, poll_period.value.int_value * 1000, 1);
break;
case 10:
relay1_gpio = 2;
adv_button_register_callback_fn(BUTTON1_GPIO, button_event1_intr_callback, 1);
adv_button_register_callback_fn(BUTTON1_GPIO, button_event2_intr_callback, 2);
adv_button_register_callback_fn(BUTTON1_GPIO, button_event3_intr_callback, 3);
adv_button_register_callback_fn(BUTTON1_GPIO, button_simple1_intr_callback, 4);
adv_button_register_callback_fn(BUTTON1_GPIO, reset_call, 5);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(switch1_on.value.bool_value, relay1_gpio);
break;
case 11:
adv_button_create(BUTTON2_GPIO);
adv_button_create(BUTTON3_GPIO);
adv_button_register_callback_fn(BUTTON1_GPIO, button_simple1_intr_callback, 1);
adv_button_register_callback_fn(BUTTON1_GPIO, reset_call, 5);
adv_button_register_callback_fn(BUTTON2_GPIO, button_simple2_intr_callback, 1);
adv_button_register_callback_fn(BUTTON3_GPIO, button_simple3_intr_callback, 1);
gpio_enable(relay1_gpio, GPIO_OUTPUT);
relay_write(switch1_on.value.bool_value, relay1_gpio);
gpio_enable(RELAY2_GPIO, GPIO_OUTPUT);
relay_write(switch2_on.value.bool_value, RELAY2_GPIO);
gpio_enable(RELAY3_GPIO, GPIO_OUTPUT);
relay_write(switch3_on.value.bool_value, RELAY3_GPIO);
break;
default:
// A wish from compiler
break;
}
sdk_os_timer_setfn(&change_settings_timer, save_settings, NULL);
sdk_os_timer_setfn(&save_states_timer, save_states, NULL);
printf("RC >>> Hardware ready\n");
wifi_config_init("RavenCore", NULL, on_wifi_ready);
}
void gpio_init() {
// Initial Setup
sysparam_status_t status;
bool bool_value;
int8_t int8_value;
int32_t int32_value;
// Load Saved Settings and set factory values for missing settings
printf("RC >>> Loading settings\n");
status = sysparam_get_bool("show_setup", &bool_value);
if (status == SYSPARAM_OK) {
show_setup.value.bool_value = bool_value;
} else {
sysparam_set_bool("show_setup", false);
}
status = sysparam_get_int8("device_type", &int8_value);
if (status == SYSPARAM_OK) {
device_type.value.int_value = int8_value;
device_type_static = int8_value;
printf("RC >>> Loading device_type -> %i\n", device_type.value.int_value);
} else {
sysparam_set_int8("device_type", 1);
printf("RC >>> Setting device_type to default -> 1\n");
}
status = sysparam_get_bool("gpio14_toggle", &bool_value);
if (status == SYSPARAM_OK) {
gpio14_toggle.value.bool_value = bool_value;
} else {
sysparam_set_bool("gpio14_toggle", false);
}
status = sysparam_get_int8("dht_sensor_type", &int8_value);
if (status == SYSPARAM_OK) {
dht_sensor_type.value.int_value = int8_value;
} else {
sysparam_set_int8("dht_sensor_type", 2);
}
status = sysparam_get_int8("poll_period", &int8_value);
if (status == SYSPARAM_OK) {
poll_period.value.int_value = int8_value;
} else {
sysparam_set_int8("poll_period", 30);
}
status = sysparam_get_int8("valve_type", &int8_value);
if (status == SYSPARAM_OK) {
valve_type.value.int_value = int8_value;
custom_valve_type.value.int_value = int8_value;
} else {
sysparam_set_int8("valve_type", 0);
}
status = sysparam_get_int8("garagedoor_working_time", &int8_value);
if (status == SYSPARAM_OK) {
custom_garagedoor_working_time.value.int_value = int8_value;
} else {
sysparam_set_int8("garagedoor_working_time", 20);
}
status = sysparam_get_bool("garagedoor_has_stop", &bool_value);
if (status == SYSPARAM_OK) {
custom_garagedoor_has_stop.value.bool_value = bool_value;
} else {
sysparam_set_bool("garagedoor_has_stop", false);
}
status = sysparam_get_bool("garagedoor_sensor_close_nc", &bool_value);
if (status == SYSPARAM_OK) {
custom_garagedoor_sensor_close_nc.value.bool_value = bool_value;
} else {
sysparam_set_bool("garagedoor_sensor_close_nc", false);
}
status = sysparam_get_bool("garagedoor_sensor_open_nc", &bool_value);
if (status == SYSPARAM_OK) {
custom_garagedoor_sensor_open_nc.value.bool_value = bool_value;
} else {
sysparam_set_bool("garagedoor_sensor_open_nc", false);
}
status = sysparam_get_bool("garagedoor_has_sensor_open", &bool_value);
if (status == SYSPARAM_OK) {
custom_garagedoor_has_sensor_open.value.bool_value = bool_value;
} else {
sysparam_set_bool("garagedoor_has_sensor_open", false);
}
status = sysparam_get_bool("garagedoor_control_with_button", &bool_value);
if (status == SYSPARAM_OK) {
custom_garagedoor_control_with_button.value.bool_value = bool_value;
} else {
sysparam_set_bool("garagedoor_control_with_button", false);
}
status = sysparam_get_int8("init_state_sw1", &int8_value);
if (status == SYSPARAM_OK) {
custom_init_state_sw1.value.int_value = int8_value;
} else {
sysparam_set_int8("init_state_sw1", 0);
}
status = sysparam_get_int8("init_state_sw2", &int8_value);
if (status == SYSPARAM_OK) {
custom_init_state_sw2.value.int_value = int8_value;
} else {
sysparam_set_int8("init_state_sw2", 0);
}
status = sysparam_get_int8("init_state_sw3", &int8_value);
if (status == SYSPARAM_OK) {
custom_init_state_sw3.value.int_value = int8_value;
} else {
sysparam_set_int8("init_state_sw3", 0);
}
status = sysparam_get_int8("init_state_sw4", &int8_value);
if (status == SYSPARAM_OK) {
custom_init_state_sw4.value.int_value = int8_value;
} else {
sysparam_set_int8("init_state_sw4", 0);
}
status = sysparam_get_int8("init_state_th", &int8_value);
if (status == SYSPARAM_OK) {
custom_init_state_th.value.int_value = int8_value;
} else {
sysparam_set_int8("init_state_th", 0);
}
// Load Saved States
printf("RC >>> Loading saved states\n");
if (custom_init_state_sw1.value.int_value > 1) {
status = sysparam_get_bool("last_state_sw1", &bool_value);
if (status == SYSPARAM_OK) {
if (custom_init_state_sw1.value.int_value == 2) {
switch1_on.value.bool_value = bool_value;
} else {
switch1_on.value.bool_value = !bool_value;
}
} else {
sysparam_set_bool("last_state_sw1", false);
}
} else if (custom_init_state_sw1.value.int_value == 1) {
switch1_on.value.bool_value = true;
}
if (custom_init_state_sw2.value.int_value > 1) {
status = sysparam_get_bool("last_state_sw2", &bool_value);
if (status == SYSPARAM_OK) {
if (custom_init_state_sw2.value.int_value == 2) {
switch2_on.value.bool_value = bool_value;
} else {
switch2_on.value.bool_value = !bool_value;
}
} else {
sysparam_set_bool("last_state_sw2", false);
}
} else if (custom_init_state_sw2.value.int_value == 1) {
switch2_on.value.bool_value = true;
}
if (custom_init_state_sw3.value.int_value > 1) {
status = sysparam_get_bool("last_state_sw3", &bool_value);
if (status == SYSPARAM_OK) {
if (custom_init_state_sw3.value.int_value == 2) {
switch3_on.value.bool_value = bool_value;
} else {
switch3_on.value.bool_value = !bool_value;
}
} else {
sysparam_set_bool("last_state_sw3", false);
}
} else if (custom_init_state_sw3.value.int_value == 1) {
switch3_on.value.bool_value = true;
}
if (custom_init_state_sw4.value.int_value > 1) {
status = sysparam_get_bool("last_state_sw4", &bool_value);
if (status == SYSPARAM_OK) {
if (custom_init_state_sw4.value.int_value == 2) {
switch4_on.value.bool_value = bool_value;
} else {
switch4_on.value.bool_value = !bool_value;
}
} else {
sysparam_set_bool("last_state_sw4", false);
}
} else if (custom_init_state_sw4.value.int_value == 1) {
switch4_on.value.bool_value = true;
}
if (custom_init_state_th.value.int_value < 3) {
target_state.value.int_value = custom_init_state_th.value.int_value;
} else {
status = sysparam_get_int8("last_target_state_th", &int8_value);
if (status == SYSPARAM_OK) {
target_state.value.int_value = int8_value;
} else {
sysparam_set_int8("last_target_state_th", 0);
}
}
status = sysparam_get_int32("target_temp", &int32_value);
if (status == SYSPARAM_OK) {
target_temperature.value.float_value = int32_value * 1.00f / 100;
} else {
sysparam_set_int32("target_temp", 23 * 100);
}
status = sysparam_get_int32("set_duration", &int32_value);
if (status == SYSPARAM_OK) {
set_duration.value.int_value = int32_value;
} else {
sysparam_set_int32("set_duration", 900);
}
sdk_os_timer_setfn(&extra_func_timer, hardware_init, NULL);
sdk_os_timer_arm(&extra_func_timer, 3000, 0);
}
homekit_characteristic_t name = HOMEKIT_CHARACTERISTIC_(NAME, NULL);
homekit_characteristic_t manufacturer = HOMEKIT_CHARACTERISTIC_(MANUFACTURER, "RavenSystem");
homekit_characteristic_t serial = HOMEKIT_CHARACTERISTIC_(SERIAL_NUMBER, NULL);
homekit_characteristic_t model = HOMEKIT_CHARACTERISTIC_(MODEL, "RavenCore");
homekit_characteristic_t identify_function = HOMEKIT_CHARACTERISTIC_(IDENTIFY, identify);
homekit_characteristic_t switch1_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Switch 1");
homekit_characteristic_t switch2_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Switch 2");
homekit_characteristic_t switch3_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Switch 3");
homekit_characteristic_t switch4_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Switch 4");
homekit_characteristic_t outlet_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Outlet");
homekit_characteristic_t button_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Action Button");
homekit_characteristic_t th_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Thermostat");
homekit_characteristic_t temp_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Temperature");
homekit_characteristic_t hum_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Humidity");
homekit_characteristic_t valve_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Water Valve");
homekit_characteristic_t garage_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Garage Door");
homekit_characteristic_t setup_service_name = HOMEKIT_CHARACTERISTIC_(NAME, "Setup", .id=100);
homekit_characteristic_t device_type_name = HOMEKIT_CHARACTERISTIC_(CUSTOM_DEVICE_TYPE_NAME, "Switch Basic", .id=101);
homekit_characteristic_t firmware = HOMEKIT_CHARACTERISTIC_(FIRMWARE_REVISION, "0.5.4");
homekit_accessory_category_t accessory_category = homekit_accessory_category_switch;
void create_accessory_name() {
printf("RC >>> Creating accessory name and serial\n");
uint8_t macaddr[6];
sdk_wifi_get_macaddr(STATION_IF, macaddr);
char *name_value = malloc(17);
snprintf(name_value, 17, "RavenCore %02X%02X%02X", macaddr[3], macaddr[4], macaddr[5]);
name.value = HOMEKIT_STRING(name_value);
char *serial_value = malloc(13);
snprintf(serial_value, 13, "%02X%02X%02X%02X%02X%02X", macaddr[0], macaddr[1], macaddr[2], macaddr[3], macaddr[4], macaddr[5]);
serial.value = HOMEKIT_STRING(serial_value);
}
homekit_server_config_t config;
void create_accessory() {
printf("RC >>> Creating HomeKit accessory\n");
uint8_t service_count = 3, service_number = 2;
// Total service count
if (show_setup.value.bool_value) {
service_count++;
}
if (device_type_static == 2 || device_type_static == 3 || device_type_static == 10) {
service_count++;
} else if (device_type_static == 6) {
service_count += 2;
} else if (device_type_static == 4 || device_type_static == 9) {
service_count += 3;
}
// Accessory Category selection
if (device_type_static == 3 || device_type_static == 9) {
accessory_category = homekit_accessory_category_outlet;
} else if (device_type_static == 5) {
accessory_category = homekit_accessory_category_thermostat;
} else if (device_type_static == 7) {
accessory_category = homekit_accessory_category_sprinkler;
} else if (device_type_static == 8) {
accessory_category = homekit_accessory_category_garage;
}
homekit_accessory_t **accessories = calloc(2, sizeof(homekit_accessory_t*));
homekit_accessory_t *sonoff = accessories[0] = calloc(1, sizeof(homekit_accessory_t));
sonoff->id = 1;
sonoff->category = accessory_category;
sonoff->config_number = 000504; // Matches as example: firmware_revision 2.3.8 = 02.03.10 (octal) = config_number 020310
sonoff->services = calloc(service_count, sizeof(homekit_service_t*));
homekit_service_t *sonoff_info = sonoff->services[0] = calloc(1, sizeof(homekit_service_t));
sonoff_info->id = 1;
sonoff_info->type = HOMEKIT_SERVICE_ACCESSORY_INFORMATION;
sonoff_info->characteristics = calloc(7, sizeof(homekit_characteristic_t*));
sonoff_info->characteristics[0] = &name;
sonoff_info->characteristics[1] = &manufacturer;
sonoff_info->characteristics[2] = &serial;
sonoff_info->characteristics[3] = &model;
sonoff_info->characteristics[4] = &firmware;
sonoff_info->characteristics[5] = &identify_function;
if (device_type_static == 2) {
char *device_type_name_value = malloc(12);
snprintf(device_type_name_value, 12, "Switch Dual");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_switch1 = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_switch1->id = 8;
sonoff_switch1->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch1->primary = true;
sonoff_switch1->characteristics = calloc(4, sizeof(homekit_characteristic_t*));
sonoff_switch1->characteristics[0] = &switch1_service_name;
sonoff_switch1->characteristics[1] = &switch1_on;
sonoff_switch1->characteristics[2] = &show_setup;
homekit_service_t *sonoff_switch2 = sonoff->services[2] = calloc(1, sizeof(homekit_service_t));
sonoff_switch2->id = 12;
sonoff_switch2->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch2->primary = false;
sonoff_switch2->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_switch2->characteristics[0] = &switch2_service_name;
sonoff_switch2->characteristics[1] = &switch2_on;
service_number = 3;
} else if (device_type_static == 3) {
char *device_type_name_value = malloc(14);
snprintf(device_type_name_value, 14, "Socket Button");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_outlet = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_outlet->id = 21;
sonoff_outlet->type = HOMEKIT_SERVICE_OUTLET;
sonoff_outlet->primary = true;
sonoff_outlet->characteristics = calloc(5, sizeof(homekit_characteristic_t*));
sonoff_outlet->characteristics[0] = &outlet_service_name;
sonoff_outlet->characteristics[1] = &switch1_on;
sonoff_outlet->characteristics[2] = &switch_outlet_in_use;
sonoff_outlet->characteristics[3] = &show_setup;
homekit_service_t *sonoff_button = sonoff->services[2] = calloc(1, sizeof(homekit_service_t));
sonoff_button->id = 26;
sonoff_button->type = HOMEKIT_SERVICE_STATELESS_PROGRAMMABLE_SWITCH;
sonoff_button->primary = false;
sonoff_button->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_button->characteristics[0] = &button_service_name;
sonoff_button->characteristics[1] = &button_event;
service_number = 3;
} else if (device_type_static == 4) {
char *device_type_name_value = malloc(11);
snprintf(device_type_name_value, 11, "Switch 4ch");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_switch1 = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_switch1->id = 8;
sonoff_switch1->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch1->primary = true;
sonoff_switch1->characteristics = calloc(4, sizeof(homekit_characteristic_t*));
sonoff_switch1->characteristics[0] = &switch1_service_name;
sonoff_switch1->characteristics[1] = &switch1_on;
sonoff_switch1->characteristics[2] = &show_setup;
homekit_service_t *sonoff_switch2 = sonoff->services[2] = calloc(1, sizeof(homekit_service_t));
sonoff_switch2->id = 12;
sonoff_switch2->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch2->primary = false;
sonoff_switch2->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_switch2->characteristics[0] = &switch2_service_name;
sonoff_switch2->characteristics[1] = &switch2_on;
homekit_service_t *sonoff_switch3 = sonoff->services[3] = calloc(1, sizeof(homekit_service_t));
sonoff_switch3->id = 15;
sonoff_switch3->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch3->primary = false;
sonoff_switch3->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_switch3->characteristics[0] = &switch3_service_name;
sonoff_switch3->characteristics[1] = &switch3_on;
homekit_service_t *sonoff_switch4 = sonoff->services[4] = calloc(1, sizeof(homekit_service_t));
sonoff_switch4->id = 18;
sonoff_switch4->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch4->primary = false;
sonoff_switch4->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_switch4->characteristics[0] = &switch4_service_name;
sonoff_switch4->characteristics[1] = &switch4_on;
service_number = 5;
} else if (device_type_static == 5) {
char *device_type_name_value = malloc(11);
snprintf(device_type_name_value, 11, "Thermostat");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_th = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_th->id = 29;
sonoff_th->type = HOMEKIT_SERVICE_THERMOSTAT;
sonoff_th->primary = true;
sonoff_th->characteristics = calloc(9, sizeof(homekit_characteristic_t*));
sonoff_th->characteristics[0] = &th_service_name;
sonoff_th->characteristics[1] = ¤t_temperature;
sonoff_th->characteristics[2] = &target_temperature;
sonoff_th->characteristics[3] = ¤t_state;
sonoff_th->characteristics[4] = &target_state;
sonoff_th->characteristics[5] = &units;
sonoff_th->characteristics[6] = ¤t_humidity;
sonoff_th->characteristics[7] = &show_setup;
} else if (device_type_static == 6) {
char *device_type_name_value = malloc(17);
snprintf(device_type_name_value, 17, "Switch TH Sensor");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_switch1 = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_switch1->id = 8;
sonoff_switch1->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch1->primary = true;
sonoff_switch1->characteristics = calloc(4, sizeof(homekit_characteristic_t*));
sonoff_switch1->characteristics[0] = &switch1_service_name;
sonoff_switch1->characteristics[1] = &switch1_on;
sonoff_switch1->characteristics[2] = &show_setup;
homekit_service_t *sonoff_temp = sonoff->services[2] = calloc(1, sizeof(homekit_service_t));
sonoff_temp->id = 38;
sonoff_temp->type = HOMEKIT_SERVICE_TEMPERATURE_SENSOR;
sonoff_temp->primary = false;
sonoff_temp->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_temp->characteristics[0] = &temp_service_name;
sonoff_temp->characteristics[1] = ¤t_temperature;
homekit_service_t *sonoff_hum = sonoff->services[3] = calloc(1, sizeof(homekit_service_t));
sonoff_hum->id = 41;
sonoff_hum->type = HOMEKIT_SERVICE_HUMIDITY_SENSOR;
sonoff_hum->primary = false;
sonoff_hum->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_hum->characteristics[0] = &hum_service_name;
sonoff_hum->characteristics[1] = ¤t_humidity;
service_number = 4;
} else if (device_type_static == 7) {
char *device_type_name_value = malloc(12);
snprintf(device_type_name_value, 12, "Water Valve");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_valve = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_valve->id = 44;
sonoff_valve->type = HOMEKIT_SERVICE_VALVE;
sonoff_valve->primary = true;
sonoff_valve->characteristics = calloc(8, sizeof(homekit_characteristic_t*));
sonoff_valve->characteristics[0] = &valve_service_name;
sonoff_valve->characteristics[1] = &active;
sonoff_valve->characteristics[2] = &in_use;
sonoff_valve->characteristics[3] = &valve_type;
sonoff_valve->characteristics[4] = &set_duration;
sonoff_valve->characteristics[5] = &remaining_duration;
sonoff_valve->characteristics[6] = &show_setup;
} else if (device_type_static == 8) {
char *device_type_name_value = malloc(12);
snprintf(device_type_name_value, 12, "Garage Door");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_garage = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_garage->id = 52;
sonoff_garage->type = HOMEKIT_SERVICE_GARAGE_DOOR_OPENER;
sonoff_garage->primary = true;
sonoff_garage->characteristics = calloc(6, sizeof(homekit_characteristic_t*));
sonoff_garage->characteristics[0] = &garage_service_name;
sonoff_garage->characteristics[1] = ¤t_door_state;
sonoff_garage->characteristics[2] = &target_door_state;
sonoff_garage->characteristics[3] = &obstruction_detected;
sonoff_garage->characteristics[4] = &show_setup;
} else if (device_type_static == 9) {
char *device_type_name_value = malloc(17);
snprintf(device_type_name_value, 17, "Socket Button TH");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_outlet = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_outlet->id = 21;
sonoff_outlet->type = HOMEKIT_SERVICE_OUTLET;
sonoff_outlet->primary = true;
sonoff_outlet->characteristics = calloc(5, sizeof(homekit_characteristic_t*));
sonoff_outlet->characteristics[0] = &outlet_service_name;
sonoff_outlet->characteristics[1] = &switch1_on;
sonoff_outlet->characteristics[2] = &switch_outlet_in_use;
sonoff_outlet->characteristics[3] = &show_setup;
homekit_service_t *sonoff_button = sonoff->services[2] = calloc(1, sizeof(homekit_service_t));
sonoff_button->id = 26;
sonoff_button->type = HOMEKIT_SERVICE_STATELESS_PROGRAMMABLE_SWITCH;
sonoff_button->primary = false;
sonoff_button->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_button->characteristics[0] = &button_service_name;
sonoff_button->characteristics[1] = &button_event;
homekit_service_t *sonoff_temp = sonoff->services[3] = calloc(1, sizeof(homekit_service_t));
sonoff_temp->id = 38;
sonoff_temp->type = HOMEKIT_SERVICE_TEMPERATURE_SENSOR;
sonoff_temp->primary = false;
sonoff_temp->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_temp->characteristics[0] = &temp_service_name;
sonoff_temp->characteristics[1] = ¤t_temperature;
homekit_service_t *sonoff_hum = sonoff->services[4] = calloc(1, sizeof(homekit_service_t));
sonoff_hum->id = 41;
sonoff_hum->type = HOMEKIT_SERVICE_HUMIDITY_SENSOR;
sonoff_hum->primary = false;
sonoff_hum->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_hum->characteristics[0] = &hum_service_name;
sonoff_hum->characteristics[1] = ¤t_humidity;
service_number = 5;
} else if (device_type_static == 10) {
char *device_type_name_value = malloc(17);
snprintf(device_type_name_value, 17, "ESP01 Switch Btn");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_switch1 = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_switch1->id = 8;
sonoff_switch1->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch1->primary = true;
sonoff_switch1->characteristics = calloc(4, sizeof(homekit_characteristic_t*));
sonoff_switch1->characteristics[0] = &switch1_service_name;
sonoff_switch1->characteristics[1] = &switch1_on;
sonoff_switch1->characteristics[2] = &show_setup;
homekit_service_t *sonoff_button = sonoff->services[2] = calloc(1, sizeof(homekit_service_t));
sonoff_button->id = 26;
sonoff_button->type = HOMEKIT_SERVICE_STATELESS_PROGRAMMABLE_SWITCH;
sonoff_button->primary = false;
sonoff_button->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_button->characteristics[0] = &button_service_name;
sonoff_button->characteristics[1] = &button_event;
service_number = 3;
} else if (device_type_static == 11) {
char *device_type_name_value = malloc(11);
snprintf(device_type_name_value, 11, "Switch 3ch");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_switch1 = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_switch1->id = 8;
sonoff_switch1->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch1->primary = true;
sonoff_switch1->characteristics = calloc(4, sizeof(homekit_characteristic_t*));
sonoff_switch1->characteristics[0] = &switch1_service_name;
sonoff_switch1->characteristics[1] = &switch1_on;
sonoff_switch1->characteristics[2] = &show_setup;
homekit_service_t *sonoff_switch2 = sonoff->services[2] = calloc(1, sizeof(homekit_service_t));
sonoff_switch2->id = 12;
sonoff_switch2->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch2->primary = false;
sonoff_switch2->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_switch2->characteristics[0] = &switch2_service_name;
sonoff_switch2->characteristics[1] = &switch2_on;
homekit_service_t *sonoff_switch3 = sonoff->services[3] = calloc(1, sizeof(homekit_service_t));
sonoff_switch3->id = 15;
sonoff_switch3->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch3->primary = false;
sonoff_switch3->characteristics = calloc(3, sizeof(homekit_characteristic_t*));
sonoff_switch3->characteristics[0] = &switch3_service_name;
sonoff_switch3->characteristics[1] = &switch3_on;
service_number = 4;
} else { // device_type_static == 1
char *device_type_name_value = malloc(13);
snprintf(device_type_name_value, 13, "Switch Basic");
device_type_name.value = HOMEKIT_STRING(device_type_name_value);
homekit_service_t *sonoff_switch1 = sonoff->services[1] = calloc(1, sizeof(homekit_service_t));
sonoff_switch1->id = 8;
sonoff_switch1->type = HOMEKIT_SERVICE_SWITCH;
sonoff_switch1->primary = true;
sonoff_switch1->characteristics = calloc(4, sizeof(homekit_characteristic_t*));
sonoff_switch1->characteristics[0] = &switch1_service_name;
sonoff_switch1->characteristics[1] = &switch1_on;
sonoff_switch1->characteristics[2] = &show_setup;
}
// Setup Accessory, visible only in 3party Apps
if (show_setup.value.bool_value) {
printf("RC >>> Creating Setup accessory\n");
homekit_service_t *sonoff_setup = sonoff->services[service_number] = calloc(1, sizeof(homekit_service_t));
sonoff_setup->id = 99;
sonoff_setup->type = HOMEKIT_SERVICE_CUSTOM_SETUP;
sonoff_setup->primary = false;
uint8_t setting_count = 5, setting_number = 4;
switch (device_type_static) {
case 2:
setting_count += 2;
break;
case 3:
setting_count += 1;
break;
case 4:
setting_count += 4;
break;
case 5:
setting_count += 3;
break;
case 6:
setting_count += 3;
break;
case 7:
setting_count += 1;
break;
case 8:
setting_count += 6;
break;
case 9:
setting_count += 3;
break;
case 10:
setting_count += 1;
break;
case 11:
setting_count += 3;
break;
default: // device_type_static == 1
setting_count += 2;
break;
}
sysparam_status_t status;
char *char_value;
status = sysparam_get_string("ota_repo", &char_value);
if (status == SYSPARAM_OK) {
setting_count++;
}
sonoff_setup->characteristics = calloc(setting_count, sizeof(homekit_characteristic_t*));
sonoff_setup->characteristics[0] = &setup_service_name;
sonoff_setup->characteristics[1] = &device_type_name;
sonoff_setup->characteristics[2] = &device_type;
sonoff_setup->characteristics[3] = &reboot_device;
if (status == SYSPARAM_OK) {
sonoff_setup->characteristics[setting_number] = &ota_firmware;
setting_number++;
}
if (device_type_static == 1) {
sonoff_setup->characteristics[setting_number] = &gpio14_toggle;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw1;
} else if (device_type_static == 2) {
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw1;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw2;
} else if (device_type_static == 3) {
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw1;
} else if (device_type_static == 4) {
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw1;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw2;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw3;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw4;
} else if (device_type_static == 5) {
sonoff_setup->characteristics[setting_number] = &dht_sensor_type;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_init_state_th;
setting_number++;
sonoff_setup->characteristics[setting_number] = &poll_period;
} else if (device_type_static == 6) {
sonoff_setup->characteristics[setting_number] = &dht_sensor_type;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw1;
setting_number++;
sonoff_setup->characteristics[setting_number] = &poll_period;
} else if (device_type_static == 7) {
sonoff_setup->characteristics[setting_number] = &custom_valve_type;
} else if (device_type_static == 8) {
sonoff_setup->characteristics[setting_number] = &custom_garagedoor_has_stop;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_garagedoor_sensor_close_nc;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_garagedoor_sensor_open_nc;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_garagedoor_has_sensor_open;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_garagedoor_working_time;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_garagedoor_control_with_button;
} else if (device_type_static == 9) {
sonoff_setup->characteristics[setting_number] = &dht_sensor_type;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw1;
setting_number++;
sonoff_setup->characteristics[setting_number] = &poll_period;
} else if (device_type_static == 10) {
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw1;
} else if (device_type_static == 11) {
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw1;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw2;
setting_number++;
sonoff_setup->characteristics[setting_number] = &custom_init_state_sw3;
}
}
config.accessories = accessories;
config.password = "<PASSWORD>";
printf("RC >>> Starting HomeKit Server\n");
homekit_server_init(&config);
}
void on_wifi_ready() {
led_code(LED_GPIO, WIFI_CONNECTED);
create_accessory_name();
create_accessory();
}
void user_init(void) {
uart_set_baud(0, 115200);
printf("RC >>> RavenCore firmware loaded\n");
printf("RC >>> Developed by RavenSystem - <NAME>\n");
printf("RC >>> Firmware revision: %s\n\n", firmware.value.string_value);
gpio_init();
}
|
numaru/hello-cortex-m | src/main.c | #include <stdbool.h>
#include <stdio.h>
#include "stm32f1xx_hal.h"
void SysTick_Handler(void)
{
}
int main(int argc, char *argv[])
{
HAL_Init();
printf("Hello World\n");
while (true)
{
}
return 0;
}
|
numaru/hello-cortex-m | src/retarget.c | <filename>src/retarget.c
#include <stdbool.h>
#include <stdint.h>
#include "stm32f1xx_hal.h"
#define USARTx USART2
#define USARTx_CLK_ENABLE() __HAL_RCC_USART2_CLK_ENABLE();
#define USARTx_RX_GPIO_CLK_ENABLE() __HAL_RCC_GPIOA_CLK_ENABLE()
#define USARTx_TX_GPIO_CLK_ENABLE() __HAL_RCC_GPIOA_CLK_ENABLE()
#define USARTx_FORCE_RESET() __HAL_RCC_USART2_FORCE_RESET()
#define USARTx_RELEASE_RESET() __HAL_RCC_USART2_RELEASE_RESET()
#define USARTx_TX_PIN GPIO_PIN_2
#define USARTx_TX_GPIO_PORT GPIOA
#define USARTx_RX_PIN GPIO_PIN_3
#define USARTx_RX_GPIO_PORT GPIOA
static UART_HandleTypeDef g_uartHandle;
int _write(int fd, char *buffer, int length)
{
for (size_t i = 0; i < length; i++)
{
HAL_UART_Transmit(&g_uartHandle, (uint8_t *)&(buffer[i]), 1, 0xFFFF);
}
return length;
}
void HAL_MspInit(void)
{
g_uartHandle.Instance = USARTx;
g_uartHandle.Init.BaudRate = 9600;
g_uartHandle.Init.WordLength = UART_WORDLENGTH_8B;
g_uartHandle.Init.StopBits = UART_STOPBITS_1;
g_uartHandle.Init.Parity = UART_PARITY_ODD;
g_uartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
g_uartHandle.Init.Mode = UART_MODE_TX_RX;
if (HAL_UART_Init(&g_uartHandle) != HAL_OK)
{
while (true)
{
}
}
}
void HAL_UART_MspInit(UART_HandleTypeDef *huart)
{
GPIO_InitTypeDef GPIO_InitStruct;
USARTx_TX_GPIO_CLK_ENABLE();
USARTx_RX_GPIO_CLK_ENABLE();
USARTx_CLK_ENABLE();
GPIO_InitStruct.Pin = USARTx_TX_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(USARTx_TX_GPIO_PORT, &GPIO_InitStruct);
GPIO_InitStruct.Pin = USARTx_RX_PIN;
HAL_GPIO_Init(USARTx_RX_GPIO_PORT, &GPIO_InitStruct);
}
void HAL_UART_MspDeInit(UART_HandleTypeDef *huart)
{
USARTx_FORCE_RESET();
USARTx_RELEASE_RESET();
HAL_GPIO_DeInit(USARTx_TX_GPIO_PORT, USARTx_TX_PIN);
HAL_GPIO_DeInit(USARTx_RX_GPIO_PORT, USARTx_RX_PIN);
}
|
vosdev/cilium-cli | vendor/github.com/petermattis/goid/goid_go1.3.c | // Copyright 2015 <NAME>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License. See the AUTHORS file
// for names of contributors.
// +build !go1.4
#include <runtime.h>
void ·Get(int64 ret) {
ret = g->goid;
USED(&ret);
}
|
aabmass/opentelemetry-operations-cpp | exporters/trace/gcp_exporter/recordable.h | #pragma once
#include "google/devtools/cloudtrace/v2/tracing.grpc.pb.h"
#include "opentelemetry/sdk/trace/recordable.h"
#include "opentelemetry/version.h"
#include "opentelemetry/nostd/variant.h"
constexpr char kProjectsPathStr[] = "projects/";
constexpr char kTracesPathStr[] = "/traces/";
constexpr char kSpansPathStr[] = "/spans/";
constexpr char kGCPEnvVar[] = "GOOGLE_CLOUD_PROJECT_ID";
OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace gcp
{
class Recordable final : public sdk::trace::Recordable
{
public:
const google::devtools::cloudtrace::v2::Span &span() const noexcept { return span_; }
void SetIds(opentelemetry::trace::TraceId trace_id,
opentelemetry::trace::SpanId span_id,
opentelemetry::trace::SpanId parent_span_id) noexcept override;
void SetAttribute(nostd::string_view key,
const opentelemetry::common::AttributeValue &value) noexcept override;
void AddEvent(
nostd::string_view name,
core::SystemTimestamp timestamp,
const opentelemetry::common::KeyValueIterable &attributes) noexcept override;
void AddLink(
const opentelemetry::trace::SpanContext &span_context,
const opentelemetry::common::KeyValueIterable &attributes) noexcept override;
void SetStatus(opentelemetry::trace::CanonicalCode code,
nostd::string_view description) noexcept override;
void SetName(nostd::string_view name) noexcept override;
void SetStartTime(opentelemetry::core::SystemTimestamp start_time) noexcept override;
void SetDuration(std::chrono::nanoseconds duration) noexcept override;
private:
google::devtools::cloudtrace::v2::Span span_;
};
} // gcp
} // exporter
OPENTELEMETRY_END_NAMESPACE |
azadeh-afzar/CCN-IRIBU | src/ccnl-utils/src/ccnl-common.c | <gh_stars>10-100
/*
* @f util/ccnl-common.c
* @b common functions for the CCN-lite utilities
*
* Copyright (C) 2013-15, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2013-07-22 created
* 2013-10-17 extended <<EMAIL>>
*/
#ifndef CCNL_UAPI_H_ // if CCNL_UAPI_H_ is defined then the following config is taken care elsewhere in the code composite
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#define _SVID_SOURCE
//#if defined(USE_FRAG) || defined(USE_MGMT) || defined(USE_SIGNATURES)
//# define NEEDS_PACKET_CRAFTING
//#endif
// ----------------------------------------------------------------------
//#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <limits.h>
//extern int getline(char **lineptr, size_t *n, FILE *stream);
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/un.h>
#include "base64.h"
//#include "base64.c"
#include "ccnl-os-includes.h"
#include "ccnl-defs.h"
#include "ccnl-core.h"
#include "ccnl-pkt-builder.h"
//#include "ccnl-ext.h"
#include "ccnl-malloc.h"
#include "ccnl-os-time.h"
#include "ccnl-logging.h"
#include "ccnl-pkt-builder.h"
int debug_level = WARNING;
#ifndef USE_DEBUG_MALLOC
#define ccnl_malloc(s) malloc(s)
#define ccnl_calloc(n,s) calloc(n,s)
#define ccnl_realloc(p,s) realloc(p,s)
#define ccnl_free(p) free(p)
#endif //USE_DEBUG_MALLOC
#define free_2ptr_list(a,b) ccnl_free(a), ccnl_free(b)
struct ccnl_prefix_s* ccnl_prefix_new(char suite, uint32_t cnt);
int ccnl_pkt_prependComponent(int suite, char *src, int *offset, unsigned char *buf);
//#include "../ccnl-pkt-switch.c"
#include "ccnl-core.h"
#include "ccnl-pkt-ccnb.h"
#include "ccnl-pkt-ccntlv.h"
#include "ccnl-pkt-localrpc.h"
#include "ccnl-pkt-ndntlv.h"
#include "ccnl-pkt-switch.h"
#include "ccnl-socket.c"
// include only the utils, not the core routines:
#ifdef USE_FRAG
#include "../ccnl-frag.h"
#endif
#else // CCNL_UAPI_H_ is defined
#include "base64.c"
#ifdef RIOT_VERSION
#include "ccnl-defs.h"
#include "net/packet.h"
#include <unistd.h>
#include "sys/socket.h"
#include "ccn-lite-riot.h"
#include "ccnl-headers.h"
#include "ccnl-pkt-ndntlv.h"
#include "ccnl-pkt-ccntlv.h"
#include "ccnl-pkt-ccnb.h"
int debug_level = WARNING;
extern int ccnl_suite2defaultPort(int suite);
#endif
#endif // CCNL_UAPI_H_
// ----------------------------------------------------------------------
const char*
ccnl_enc2str(int enc)
{
switch(enc) {
case CCNL_ENC_CCNB: return CONSTSTR("ccnb");
case CCNL_ENC_NDN2013: return CONSTSTR("ndn2013");
case CCNL_ENC_CCNX2014: return CONSTSTR("ccnbx2014");
case CCNL_ENC_LOCALRPC: return CONSTSTR("localrpc");
default:
break;
}
return CONSTSTR("?");
}
// ----------------------------------------------------------------------
#define extractStr(VAR,DTAG) \
if (typ == CCN_TT_DTAG && num == DTAG) { \
char *s; unsigned char *valptr; int vallen; \
if (ccnl_ccnb_consume(typ, num, &buf, &buflen, &valptr, &vallen) < 0) \
goto Bail; \
s = ccnl_malloc(vallen+1); if (!s) goto Bail; \
memcpy(s, valptr, vallen); s[vallen] = '\0'; \
ccnl_free(VAR); \
VAR = (unsigned char*) s; \
continue; \
} do {} while(0)
#define extractStr2(VAR,DTAG) \
if (typ == CCN_TT_DTAG && num == DTAG) { \
char *s; unsigned char *valptr; int vallen; \
if (ccnl_ccnb_consume(typ, num, buf, buflen, &valptr, &vallen) < 0) \
goto Bail; \
s = ccnl_malloc(vallen+1); if (!s) goto Bail; \
memcpy(s, valptr, vallen); s[vallen] = '\0'; \
ccnl_free(VAR); \
VAR = (unsigned char*) s; \
continue; \
} do {} while(0)
// ----------------------------------------------------------------------
struct key_s {
struct key_s *next;
unsigned char* key;
int keylen;
};
struct key_s*
load_keys_from_file(char *path)
{
FILE *fp = fopen(path, "r");
char line[256];
int cnt = 0;
struct key_s *klist = NULL, *kend = NULL;
if (!fp) {
perror("file open");
return NULL;
}
while (fgets(line, sizeof(line), fp)) {
unsigned char *key;
size_t keylen;
int read = strlen(line);
DEBUGMSG(TRACE, " read %d bytes\n", read);
if (line[read-1] == '\n')
line[--read] = '\0';
key = base64_decode(line, read, &keylen);
if (key && keylen > 0) {
struct key_s *k = (struct key_s *) calloc(1, sizeof(struct key_s));
k->keylen = keylen;
k->key = key;
if (kend)
kend->next = k;
else
klist = k;
kend = k;
cnt++;
DEBUGMSG(VERBOSE, " key #%d: %d bytes\n", cnt, (int)keylen);
if (keylen < 32) {
DEBUGMSG(WARNING, "key #%d: should choose a longer key!\n", cnt);
}
}
}
fclose(fp);
DEBUGMSG(DEBUG, "read %d keys from file %s\n", cnt, optarg);
return klist;
}
// ----------------------------------------------------------------------
int
ccnl_parseUdp(char *udp, int suite, char **addr, int *port)
{
char *tmpAddr = NULL;
char *tmpPortStr = NULL;
char *end = NULL;
int tmpPort;
if (!udp) {
*addr = "127.0.0.1";
*port = ccnl_suite2defaultPort(suite);
return 0;
}
if (!strchr(udp, '/')) {
DEBUGMSG(ERROR, "invalid UDP destination, missing port: %s\n", udp);
return -1;
}
tmpAddr = strtok(udp, "/");
tmpPortStr = strtok(NULL, "/");
if (!tmpPortStr) {
DEBUGMSG(ERROR, "invalid UDP destination, empty UDP port: %s/\n", udp);
return -1;
}
tmpPort = strtol(tmpPortStr, &end, 10);
if (*end != '\0') {
DEBUGMSG(ERROR, "invalid UDP destination, cannot parse port as number: %s\n", tmpPortStr);
return -1;
}
*addr = tmpAddr;
*port = tmpPort;
return 0;
}
// eof
|
azadeh-afzar/CCN-IRIBU | src/ccnl-utils/include/ccnl-socket.h | /**
* @addtogroup CCNL-utils
* @{
*
* @file ccnl-socket.h
* @brief Request content: send an interest open socket etc
*
* Copyright (C) 2013-18, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_SOCKET_H
#define CCNL_SOCKET_H
#include <ctype.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void myexit(int rc);
int udp_open(void);
int udp_sendto(int sock, char *dest, unsigned char *data, int len);
int ux_open(void);
ssize_t ux_sendto(int sock, char *topath, uint8_t *data, size_t len);
int block_on_read(int sock, float wait);
void request_content(int sock, int (*sendproc)(int,char*,unsigned char*,int),
char *dest, unsigned char *out, int len, float wait);
#endif
/** @} */
|
azadeh-afzar/CCN-IRIBU | src/ccnl-utils/include/ccnl-overflow.h | /**
* @addtogroup CCNL-utils
* @{
*
* @file ccnl-overflow.h
* @brief Provides macros for detecting integer overflows
*
* Copyright (C) 2018 <NAME>, MSA Safety
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_OVERFLOW_H
#define CCNL_OVERFLOW_H
/**
* @brief Checks if a __builtin* feature is availbale or not
*/
#ifdef __clang__
#define HAS(...) __has_builtin(__VA_ARGS__)
#elif defined __GNUC__
/** builtin is only available in gcc versions > 4 */
#if __GNUC__ > 4
#define HAS(...) 1
#else
#define HAS(...) 0
#endif
#else
#define HAS(...) 0
#endif
#if HAS(__builtin_mul_overflow)
/**
* @brief Checks if two integers can be multiplied without causing an
* integer overflow.
*
* @note This macro definition makes use of GCCs/CLANGs builtin functions
* for detecting integer overflows.
*
* @param[in] a The first operand of the operation
* @param[in] b The second operand of the operation
* @param[in] c The result of the operation
*
* @return True if an overflow would be triggered, false otherwise
*/
#define INT_MULT_OVERFLOW(a, b, c) \
__builtin_mul_overflow (a, b, c)
#else
#ifndef BUILTIN_INT_MULT_OVERFLOW_DETECTION_UNAVAILABLE
#define BUILTIN_INT_MULT_OVERFLOW_DETECTION_UNAVAILABLE (0x1u)
#endif
#endif
#if HAS(__builtin_add_overflow)
/**
* @brief Checks if two integers can be added without causing an
* integer overflow.
*
* @note This macro definition makes use of GCCs/CLANGs builtin functions
* for detecting integer overflows.
*
* @param[in] a The first operand of the operation
* @param[in] b The second operand of the operation
* @param[in] c The result of the operation
*
* @return True if an overflow would be triggered, false otherwise
*/
#define INT_ADD_OVERFLOW(a, b, c) \
__builtin_add_overflow (a, b, c)
#else
#ifndef BUILTIN_INT_ADD_OVERFLOW_DETECTION_UNAVAILABLE
#define BUILTIN_INT_ADD_OVERFLOW_DETECTION_UNAVAILABLE (0x1u)
#endif
#endif
#endif
/** @} */
|
azadeh-afzar/CCN-IRIBU | src/ccnl-riot/include/ccn-lite-riot.h | /*
* Copyright (C) 2015, 2016 INRIA
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
#ifndef CCN_LITE_RIOT_H
#define CCN_LITE_RIOT_H
/**
* @defgroup pkg_ccnlite CCN-Lite stack
* @ingroup pkg
* @ingroup net
* @brief Provides a NDN implementation
*
* This package provides the CCN-Lite stack as a port of NDN for RIOT.
*
* @{
*/
#include <unistd.h>
#include "sched.h"
#include "arpa/inet.h"
#include "net/packet.h"
#include "net/ethernet/hdr.h"
#include "sys/socket.h"
#include "ccnl-core.h"
#include "ccnl-pkt-ndntlv.h"
#include "net/gnrc/netreg.h"
#include "ccnl-dispatch.h"
//#include "ccnl-pkt-builder.h"
#include "irq.h"
#include "evtimer.h"
#include "evtimer_msg.h"
#include "thread.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name Dynamic memory allocation used in CCN-Lite
*
* @{
*/
#define ccnl_malloc(s) malloc(s)
#define ccnl_calloc(n,s) calloc(n,s)
#define ccnl_realloc(p,s) realloc(p,s)
#define ccnl_free(p) free(p)
/**
* @}
*/
/**
* Constant string
*/
#define CONSTSTR(s) s
/**
* Stack size for CCN-Lite event loop
*/
#ifndef CCNL_STACK_SIZE
#define CCNL_STACK_SIZE (THREAD_STACKSIZE_MAIN)
#endif
/**
* Size of the message queue of CCN-Lite's event loop
*/
#ifndef CCNL_QUEUE_SIZE
#define CCNL_QUEUE_SIZE (8)
#endif
/**
* Interest retransmission interval in milliseconds
*/
#ifndef CCNL_INTEREST_RETRANS_TIMEOUT
#define CCNL_INTEREST_RETRANS_TIMEOUT (1000)
#endif
/**
* @brief Data structure for interest packet
*/
typedef struct {
struct ccnl_prefix_s *prefix; /**< requested prefix */
unsigned char *buf; /**< buffer to store the interest packet */
size_t buflen; /**< size of the buffer */
} ccnl_interest_t;
/**
* PID of the eventloop thread
*/
extern kernel_pid_t ccnl_event_loop_pid;
/**
* Maximum string length for prefix representation
*/
#define CCNL_PREFIX_BUFSIZE (50)
/**
* Message type for signalling a timeout while waiting for a content chunk
*/
#define CCNL_MSG_TIMEOUT (0x1701)
/**
* Message type for advancing the ageing timer
*/
#define CCNL_MSG_AGEING (0x1702)
/**
* Message type for Interest retransmissions
*/
#define CCNL_MSG_INT_RETRANS (0x1703)
/**
* Message type for adding content store entries
*/
#define CCNL_MSG_CS_ADD (0x1704)
/**
* Message type for deleting content store entries
*/
#define CCNL_MSG_CS_DEL (0x1705)
/**
* Message type for performing a content store lookup
*/
#define CCNL_MSG_CS_LOOKUP (0x1706)
/**
* Message type for Interest timeouts
*/
#define CCNL_MSG_INT_TIMEOUT (0x1707)
/**
* Message type for Face timeouts
*/
#define CCNL_MSG_FACE_TIMEOUT (0x1708)
/**
* Maximum number of elements that can be cached
*/
#ifndef CCNL_CACHE_SIZE
#define CCNL_CACHE_SIZE (5)
#endif
#ifdef DOXYGEN
#define CCNL_CACHE_SIZE
#endif
#ifndef CCNL_THREAD_PRIORITY
#define CCNL_THREAD_PRIORITY (THREAD_PRIORITY_MAIN - 1)
#endif
/**
* Struct holding CCN-Lite's central relay information
*/
extern struct ccnl_relay_s ccnl_relay;
/**
* Struct Evtimer for various ccnl events
*/
extern evtimer_msg_t ccnl_evtimer;
/**
* @brief Start the main CCN-Lite event-loop
*
* @return The PID of the event-loop's thread
*/
kernel_pid_t ccnl_start(void);
/**
* @brief Opens a @ref net_gnrc_netif device for use with CCN-Lite
*
* @param[in] if_pid The pid of the @ref net_gnrc_netif device driver
* @param[in] netreg_type The @ref net_gnrc_nettype @p if_pid should be
* configured to use
*
* @return 0 on success,
* @return -EINVAL if eventloop could not be registered for @p netreg_type
*/
int ccnl_open_netif(kernel_pid_t if_pid, gnrc_nettype_t netreg_type);
/**
* @brief Sends out an Interest
*
* @param[in] prefix The name that is requested
* @param[out] buf Buffer to write the content chunk to
* @param[in] buf_len Size of @p buf
* @param[in] int_opts Interest options (@ref ccnl_interest_opts_u)
*
* @return 0 on success
* @return -1, packet format not supported
* @return -2, prefix is NULL
* @return -3, packet deheading failed
* @return -4, parsing failed
*/
int ccnl_send_interest(struct ccnl_prefix_s *prefix,
unsigned char *buf, int buf_len,
ccnl_interest_opts_u *int_opts);
/**
* @brief Wait for incoming content chunk
*
* @pre The thread has to register for CCNL_CONT_CHUNK in @ref net_gnrc_netreg
* first
*
* @post The thread should unregister from @ref net_gnrc_netreg after this
* function returns
*
* @param[out] buf Buffer to stores the received content
* @param[in] buf_len Size of @p buf
* @param[in] timeout Maximum to wait for the chunk, set to a default value if 0
*
* @return 0 if a content was received
* @return -ETIMEDOUT if no chunk was received until timeout
*/
int ccnl_wait_for_chunk(void *buf, size_t buf_len, uint64_t timeout);
/**
* @brief Send a message to the CCN-lite thread to add @p to the content store
*
* @param[in] content The content to add to the content store
*/
static inline void ccnl_msg_cs_add(struct ccnl_content_s *content)
{
msg_t ms = { .type = CCNL_MSG_CS_ADD, .content.ptr = content };
msg_send(&ms, ccnl_event_loop_pid);
}
/**
* @brief Send a message to the CCN-lite thread to remove a content with
* the @p prefix from the content store
*
* @param[in] content The prefix of the content to remove from the content store
*/
static inline void ccnl_msg_cs_remove(struct ccnl_prefix_s *prefix)
{
msg_t ms = { .type = CCNL_MSG_CS_DEL, .content.ptr = prefix };
msg_send(&ms, ccnl_event_loop_pid);
}
/**
* @brief Send a message to the CCN-lite thread to perform a content store
* lookup for the @p prefix
*
* @param[in] content The prefix of the content to perform a lookup for
*
* @return pointer to the content, if found
* @reutn NULL, if not found
*/
static inline struct ccnl_content_s *ccnl_msg_cs_lookup(struct ccnl_prefix_s *prefix)
{
msg_t mr, ms = { .type = CCNL_MSG_CS_LOOKUP, .content.ptr = prefix };
msg_send_receive(&ms, &mr, ccnl_event_loop_pid);
return (struct ccnl_content_s *) mr.content.ptr;
}
/**
* @brief Reset Interest retransmissions
*
* @param[in] i The interest to update
*/
static inline void ccnl_evtimer_reset_interest_retrans(struct ccnl_interest_s *i)
{
evtimer_del((evtimer_t *)(&ccnl_evtimer), (evtimer_event_t *)&i->evtmsg_retrans);
i->evtmsg_retrans.msg.type = CCNL_MSG_INT_RETRANS;
i->evtmsg_retrans.msg.content.ptr = i;
((evtimer_event_t *)&i->evtmsg_retrans)->offset = CCNL_INTEREST_RETRANS_TIMEOUT;
evtimer_add_msg(&ccnl_evtimer, &i->evtmsg_retrans, ccnl_event_loop_pid);
}
/**
* @brief Reset Interest timeout
*
* @param[in] i The interest to update
*/
static inline void ccnl_evtimer_reset_interest_timeout(struct ccnl_interest_s *i)
{
evtimer_del((evtimer_t *)(&ccnl_evtimer), (evtimer_event_t *)&i->evtmsg_timeout);
i->evtmsg_timeout.msg.type = CCNL_MSG_INT_TIMEOUT;
i->evtmsg_timeout.msg.content.ptr = i;
((evtimer_event_t *)&i->evtmsg_timeout)->offset = i->lifetime * 1000; // ms
evtimer_add_msg(&ccnl_evtimer, &i->evtmsg_timeout, ccnl_event_loop_pid);
}
/**
* @brief Reset Face timeout
*
* @param[in] f The face to update
*/
static inline void ccnl_evtimer_reset_face_timeout(struct ccnl_face_s *f)
{
evtimer_del((evtimer_t *)(&ccnl_evtimer), (evtimer_event_t *)&f->evtmsg_timeout);
f->evtmsg_timeout.msg.type = CCNL_MSG_FACE_TIMEOUT;
f->evtmsg_timeout.msg.content.ptr = f;
((evtimer_event_t *)&f->evtmsg_timeout)->offset = CCNL_FACE_TIMEOUT * 1000; // ms
evtimer_add_msg(&ccnl_evtimer, &f->evtmsg_timeout, ccnl_event_loop_pid);
}
/**
* @brief Set content timeout
*
* @param[in] c The content to timeout
*/
static inline void ccnl_evtimer_set_cs_timeout(struct ccnl_content_s *c)
{
evtimer_del((evtimer_t *)(&ccnl_evtimer), (evtimer_event_t *)&c->evtmsg_cstimeout);
c->evtmsg_cstimeout.msg.type = CCNL_MSG_CS_DEL;
c->evtmsg_cstimeout.msg.content.ptr = c->pkt->pfx;
((evtimer_event_t *)&c->evtmsg_cstimeout)->offset = CCNL_CONTENT_TIMEOUT * 1000UL; // ms
evtimer_add_msg(&ccnl_evtimer, &c->evtmsg_cstimeout, ccnl_event_loop_pid);
}
/**
* @brief Remove RIOT related structures for Interests
*
* @param[in] et RIOT related event queue that holds timer events
* @param[in] i The Interest structure
*/
static inline void ccnl_riot_interest_remove(evtimer_t *et, struct ccnl_interest_s *i)
{
evtimer_del(et, (evtimer_event_t *)&i->evtmsg_retrans);
evtimer_del(et, (evtimer_event_t *)&i->evtmsg_timeout);
unsigned state = irq_disable();
/* remove messages that relate to this interest from the message queue */
thread_t *me = thread_get_active();
for (unsigned j = 0; j <= me->msg_queue.mask; j++) {
if (me->msg_array[j].content.ptr == i) {
/* removing is done by setting to zero */
memset(&(me->msg_array[j]), 0, sizeof(me->msg_array[j]));
}
}
irq_restore(state);
}
#ifdef __cplusplus
}
#endif
#endif /* CCN_LITE_RIOT_H */
/** @} */
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-sched.h | /*
* @f ccnl-sched.h
* @b CCN lite, core CCNx protocol logic
*
* Copyright (C) 2011-18 University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_SCHED_H
#define CCNL_SCHED_H
#ifndef CCNL_LINUXKERNEL
#include <sys/time.h>
#endif
struct ccnl_relay_s;
struct ccnl_sched_s {
char mode; // 0=dummy, 1=pktrate
void (*rts)(struct ccnl_sched_s* s, int cnt, int len, void *aux1, void *aux2);
// private:
void (*cts)(void *aux1, void *aux2);
struct ccnl_relay_s *ccnl;
void *aux1, *aux2;
int cnt;
#ifdef USE_CHEMFLOW
struct cf_rnet *rn;
struct cf_queue *q;
#else
void *pendingTimer;
struct timeval nextTX;
// simple packet rate limiter:
int ipi; // inter_packet_interval, minimum time between send() in usec
#endif
};
int
ccnl_sched_init(void);
void
ccnl_sched_cleanup(void);
struct ccnl_sched_s*
ccnl_sched_dummy_new(void (cts)(void *aux1, void *aux2),struct ccnl_relay_s *ccnl);
struct ccnl_sched_s*
ccnl_sched_pktrate_new(void (cts)(void *aux1, void *aux2),
struct ccnl_relay_s *ccnl, int inter_packet_interval);
void
ccnl_sched_destroy(struct ccnl_sched_s *s);
void
ccnl_sched_RTS(struct ccnl_sched_s *s, int cnt, int len,
void *aux1, void *aux2);
void
ccnl_sched_CTS_done(struct ccnl_sched_s *s, int cnt, int len);
void
ccnl_sched_RX_ok(struct ccnl_relay_s *ccnl, int ifndx, int cnt);
void
ccnl_sched_RX_loss(struct ccnl_relay_s *ccnl, int ifndx, int cnt);
struct ccnl_sched_s*
ccnl_sched_packetratelimiter_new(int inter_packet_interval,
void (*cts)(void *aux1, void *aux2),
void *aux1, void *aux2);
#endif // EOF
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-pkt-util.h | /*
* @f ccnl-pkt-util.h
* @b Helper functions for identifying packets
*
* Copyright (C) 2011-18 University of Basel
* Copyright (C) 2018 Safety IO
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_PKT_UTIL_H
#define CCNL_PKT_UTIL_H
#ifndef CCNL_LINUXKERNEL
#include <stdint.h>
#else
#include <linux/types.h>
#endif
#include <stddef.h>
#include "ccnl-pkt.h"
uint8_t
ccnl_isSuite(int suite);
int
ccnl_suite2defaultPort(int suite);
const char*
ccnl_suite2str(int suite);
int
ccnl_str2suite(char *cp);
int
ccnl_pkt2suite(uint8_t *data, size_t len, size_t *skip);
/**
* Returns the integer representation of a string
*
* @param[in] cmp The string representation of a number
* @param[in] cmplen The length of the string
*
* @return Upon success returns the converted integral number as a long int value
* @return Upon failure the function returns 0 (e.g. if no valid conversion could be performed)
*/
int
ccnl_cmp2int(unsigned char *cmp, size_t cmplen);
/**
* Returns the Interest lifetime in seconds
*
* @param[in] pkt Pointer to the Interest packet
*
* @return The interest lifetime in seconds
*/
uint64_t
ccnl_pkt_interest_lifetime(const struct ccnl_pkt_s *pkt);
#endif
|
azadeh-afzar/CCN-IRIBU | test/ccnl-core/test_producer.c | /**
* @file test-producer.c
* @brief CCN lite - Tests for the local producer functions
*
* Copyright (C) 2018 MSA Safety
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "ccnl-producer.h"
int _test_local_producer(struct ccnl_relay_s *relay, struct ccnl_face_s *from,
struct ccnl_pkt_s *pkt);
int _test_local_producer(struct ccnl_relay_s *relay, struct ccnl_face_s *from,
struct ccnl_pkt_s *pkt)
{
/* we don't care about the parameters */
(void)relay;
(void)from;
(void)pkt;
/* we don't really care about creating content on demand for test purposes */
return 1;
}
void test_local_producer_is_set()
{
/* parameters shouldn't matter in this example */
int result = local_producer(NULL, NULL, NULL);
/* function returns 0 if no producer function has been set */
assert_int_equal(result, 0);
/* set producer function */
ccnl_set_local_producer(&_test_local_producer);
/* call the function again */
result = local_producer(NULL, NULL, NULL);
/* should return 1 instead */
assert_int_equal(result, 1);
/* unset function */
ccnl_set_local_producer(NULL);
}
void test_local_producer_is_not_set()
{
/* again, parameters shouldn't matter in this example */
int result = local_producer(NULL, NULL, NULL);
/* function returns 0 if no producer function has been set */
assert_int_equal(result, 0);
}
int main(void)
{
const UnitTest tests[] = {
unit_test(test_local_producer_is_set),
unit_test(test_local_producer_is_not_set),
};
return run_tests(tests);
}
|
azadeh-afzar/CCN-IRIBU | test/ccnl-core/test_pkt-util.c | /**
* @file test_pkt-util.c
* @brief Tests for packet util functions
*
* Copyright (C) 2018 Safety IO
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "ccnl-defs.h"
#include "ccnl-pkt-ccntlv.h"
#include "ccnl-pkt-ndntlv.h"
#include "ccnl-pkt-util.h"
#define USE_SUITE_CCNB 0x01
#define USE_SUITE_NDNTLV 0x06
#define USE_SUITE_CCNTLV 0x02
#define USE_SUITE_LOCALRPC 0x05
#define CCNL_SUITE_CCNB 0x01
#define CCNL_SUITE_CCNTLV 0x02
#define CCNL_SUITE_LOCALRPC 0x05
#define CCNL_SUITE_NDNTLV 0x06
void test_ccnl_is_suite_invalid()
{
int invalid_suite = 0x42;
int result = ccnl_isSuite(invalid_suite);
assert_false(result);
}
void test_ccnl_is_suite_valid()
{
int valid_suite = USE_SUITE_CCNB;
int result = ccnl_isSuite(valid_suite);
assert_true(result);
valid_suite = USE_SUITE_CCNTLV;
result = ccnl_isSuite(valid_suite);
assert_true(result);
valid_suite = USE_SUITE_LOCALRPC;
result = ccnl_isSuite(valid_suite);
assert_true(result);
valid_suite = USE_SUITE_NDNTLV;
result = ccnl_isSuite(valid_suite);
assert_true(result);
}
void test_ccnl_suite2default_port_invalid()
{
int invalid_suite = 0x42;
int result = ccnl_suite2defaultPort(invalid_suite);
/** returns by default \ref NDN_UDP_PORT */
assert_int_equal(result, NDN_UDP_PORT);
}
void test_ccnl_suite2default_port_valid()
{
int valid_suite = USE_SUITE_NDNTLV;
int result = ccnl_suite2defaultPort(valid_suite);
assert_int_equal(result, NDN_UDP_PORT);
valid_suite = USE_SUITE_CCNB;
result = ccnl_suite2defaultPort(valid_suite);
assert_int_equal(result, CCN_UDP_PORT);
valid_suite = USE_SUITE_CCNTLV;
result = ccnl_suite2defaultPort(valid_suite);
assert_int_equal(result, CCN_UDP_PORT);
}
void test_ccnl_suite2str_invalid()
{
int invalid_suite = 0x42;
const char *result = ccnl_suite2str(invalid_suite);
assert_string_equal(result, "?");
}
void test_ccnl_suite2str_valid()
{
int valid_suite = USE_SUITE_NDNTLV;
const char* ndn_result = ccnl_suite2str(valid_suite);
assert_string_equal(ndn_result, "ndn2013");
valid_suite = USE_SUITE_CCNB;
const char* ccnb_result = ccnl_suite2str(valid_suite);
assert_string_equal(ccnb_result, "ccnb");
valid_suite = USE_SUITE_CCNTLV;
const char* ccn_result = ccnl_suite2str(valid_suite);
assert_string_equal(ccn_result, "ccnx2015");
valid_suite = USE_SUITE_LOCALRPC;
const char* local_rpc_result = ccnl_suite2str(valid_suite);
assert_string_equal(local_rpc_result, "localrpc");
}
void test_ccnl_str2suite_invalid()
{
int result = ccnl_str2suite("invalid");
assert_int_equal(result, -1);
}
void test_ccnl_str2suite_valid()
{
int result = ccnl_str2suite("ccnb");
assert_int_equal(result, CCNL_SUITE_CCNB);
result = ccnl_str2suite("ccnx2015");
assert_int_equal(result, CCNL_SUITE_CCNTLV);
result = ccnl_str2suite("localrpc");
assert_int_equal(result, CCNL_SUITE_LOCALRPC);
result = ccnl_str2suite("ndn2013");
assert_int_equal(result, CCNL_SUITE_NDNTLV);
}
void test_ccnl_cmp2int_invalid()
{
int result = ccnl_cmp2int(NULL, 42);
assert_int_equal(result, 0);
}
void test_ccnl_cmp2int_valid()
{
int result = ccnl_cmp2int("42", 2);
assert_int_equal(result, 42);
/** if we pass a larger than actual size number it is still 42 */
result = ccnl_cmp2int("42", 42);
assert_int_equal(result, 42);
/** if we pass a less than it is the first digit */
result = ccnl_cmp2int("42", 1);
assert_int_equal(result, 4);
}
void test_ccnl_pkt2suite_invalid()
{
int result = ccnl_pkt2suite(NULL, 0, NULL);
/** length is invalid */
assert_int_equal(result, -1);
}
void test_ccnl_pkt2suite_valid()
{
char buffer[2];
buffer[0] = CCNL_SUITE_NDNTLV;
buffer[1] = 0x01;
int result = ccnl_pkt2suite(buffer, 2, NULL);
assert_int_equal(result, CCNL_SUITE_NDNTLV);
buffer[0] = 0x04;
result = ccnl_pkt2suite(buffer, 2, NULL);
assert_int_equal(result, CCNL_SUITE_CCNB);
buffer[0] = CCNX_TLV_V1;
result = ccnl_pkt2suite(buffer, 2, NULL);
assert_int_equal(result, CCNL_SUITE_CCNTLV);
}
int main(void)
{
const UnitTest tests[] = {
unit_test(test_ccnl_is_suite_invalid),
unit_test(test_ccnl_is_suite_valid),
unit_test(test_ccnl_suite2default_port_invalid),
unit_test(test_ccnl_suite2default_port_valid),
unit_test(test_ccnl_suite2str_invalid),
unit_test(test_ccnl_suite2str_valid),
unit_test(test_ccnl_str2suite_invalid),
unit_test(test_ccnl_str2suite_valid),
unit_test(test_ccnl_cmp2int_invalid),
unit_test(test_ccnl_cmp2int_valid),
unit_test(test_ccnl_pkt2suite_invalid),
unit_test(test_ccnl_pkt2suite_valid),
};
return run_tests(tests);
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/src/ccnl-pkt-util.c | <gh_stars>10-100
/*
* @f ccnl-pkt-util.c
*
* Copyright (C) 2011-15, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-20 created
*/
#ifndef CCNL_LINUXKERNEL
#include "ccnl-pkt-util.h"
#include "ccnl-defs.h"
#include "ccnl-os-time.h"
#include "ccnl-pkt-ccnb.h"
#include "ccnl-pkt-ccntlv.h"
#include "ccnl-pkt-ndntlv.h"
#include "ccnl-pkt-switch.h"
#include "ccnl-logging.h"
#else
#include "../include/ccnl-pkt-util.h"
#include "../include/ccnl-defs.h"
#include "../include/ccnl-os-time.h"
#include "../../ccnl-pkt/include/ccnl-pkt-ccnb.h"
#include "../../ccnl-pkt/include/ccnl-pkt-ccntlv.h"
#include "../../ccnl-pkt/include/ccnl-pkt-ndntlv.h"
#include "../../ccnl-pkt/include/ccnl-pkt-switch.h"
#include "../include/ccnl-logging.h"
#endif
int
ccnl_str2suite(char *cp)
{
if (!cp)
return -1;
#ifdef USE_SUITE_CCNB
if (!strcmp(cp, CONSTSTR("ccnb")))
return CCNL_SUITE_CCNB;
#endif
#ifdef USE_SUITE_CCNTLV
if (!strcmp(cp, CONSTSTR("ccnx2015")))
return CCNL_SUITE_CCNTLV;
#endif
#ifdef USE_SUITE_LOCALRPC
if (!strcmp(cp, CONSTSTR("localrpc")))
return CCNL_SUITE_LOCALRPC;
#endif
#ifdef USE_SUITE_NDNTLV
if (!strcmp(cp, CONSTSTR("ndn2013")))
return CCNL_SUITE_NDNTLV;
#endif
return -1;
}
const char*
ccnl_suite2str(int suite)
{
#ifdef USE_SUITE_CCNB
if (suite == CCNL_SUITE_CCNB)
return CONSTSTR("ccnb");
#endif
#ifdef USE_SUITE_CCNTLV
if (suite == CCNL_SUITE_CCNTLV)
return CONSTSTR("ccnx2015");
#endif
#ifdef USE_SUITE_LOCALRPC
if (suite == CCNL_SUITE_LOCALRPC)
return CONSTSTR("localrpc");
#endif
#ifdef USE_SUITE_NDNTLV
if (suite == CCNL_SUITE_NDNTLV)
return CONSTSTR("ndn2013");
#endif
return CONSTSTR("?");
}
int
ccnl_suite2defaultPort(int suite)
{
#ifdef USE_SUITE_CCNB
if (suite == CCNL_SUITE_CCNB)
return CCN_UDP_PORT;
#endif
#ifdef USE_SUITE_CCNTLV
if (suite == CCNL_SUITE_CCNTLV)
return CCN_UDP_PORT;
#endif
#ifdef USE_SUITE_NDNTLV
if (suite == CCNL_SUITE_NDNTLV)
return NDN_UDP_PORT;
#endif
return NDN_UDP_PORT;
}
uint8_t
ccnl_isSuite(int suite)
{
#ifdef USE_SUITE_CCNB
if (suite == CCNL_SUITE_CCNB)
return true;
#endif
#ifdef USE_SUITE_CCNTLV
if (suite == CCNL_SUITE_CCNTLV)
return true;
#endif
#ifdef USE_SUITE_LOCALRPC
if (suite == CCNL_SUITE_LOCALRPC)
return true;
#endif
#ifdef USE_SUITE_NDNTLV
if (suite == CCNL_SUITE_NDNTLV)
return true;
#endif
return false;
}
int
ccnl_pkt2suite(uint8_t *data, size_t len, size_t *skip)
{
int suite = -1;
int32_t enc;
uint8_t *olddata = data;
if (skip) {
*skip = 0;
}
if (len <= 0) {
return -1;
}
DEBUGMSG_CUTL(TRACE, "pkt2suite %d %d\n", data[0], data[1]);
while (!ccnl_switch_dehead(&data, &len, &enc)) {
suite = ccnl_enc2suite(enc);
}
if (skip) {
*skip = data - olddata;
}
if (suite >= 0) {
return suite;
}
#ifdef USE_SUITE_CCNB
if (*data == 0x04) {
return CCNL_SUITE_CCNB;
}
if (*data == 0x01 && len > 1 && // check for CCNx2015 and Cisco collision:
(data[1] != 0x00 && // interest
data[1] != 0x01 && // data
data[1] != 0x02 && // interestReturn
data[1] != 0x03)) { // fragment
return CCNL_SUITE_CCNB;
}
#endif
#ifdef USE_SUITE_CCNTLV
if (data[0] == CCNX_TLV_V1 && len > 1) {
if (data[1] == CCNX_PT_Interest ||
data[1] == CCNX_PT_Data ||
data[1] == CCNX_PT_Fragment ||
data[1] == CCNX_PT_NACK) {
return CCNL_SUITE_CCNTLV;
}
}
#endif
#ifdef USE_SUITE_NDNTLV
if (*data == NDN_TLV_Interest || *data == NDN_TLV_Data ||
*data == NDN_TLV_Fragment) {
return CCNL_SUITE_NDNTLV;
}
#endif
/*
#ifdef USE_SUITE_LOCALRPC
if (*data == LRPC_PT_REQUEST || *data == LRPC_PT_REPLY) {
return CCNL_SUITE_LOCALRPC;
}
#endif
}
*/
return -1;
}
int
ccnl_cmp2int(unsigned char *cmp, size_t cmplen)
{
if (cmp) {
long int i;
char *str = (char *)ccnl_malloc(cmplen+1);
DEBUGMSG(DEBUG, " inter a: %zd\n", cmplen);
DEBUGMSG(DEBUG, " inter b\n");
memcpy(str, (char *)cmp, cmplen);
str[cmplen] = '\0';
DEBUGMSG(DEBUG, " inter c: %s\n", str);
i = strtol(str, NULL, 0);
DEBUGMSG(DEBUG, " inter d\n");
ccnl_free(str);
return (int)i;
}
return 0;
}
uint64_t
ccnl_pkt_interest_lifetime(const struct ccnl_pkt_s *pkt)
{
switch(pkt->suite) {
#ifdef USE_SUITE_CCNTLV
case CCNL_SUITE_CCNTLV:
/* CCN-TLV parser does not support lifetime parsing, yet. */
return CCNL_INTEREST_TIMEOUT;
#endif
#ifdef USE_SUITE_NDNTLV
case CCNL_SUITE_NDNTLV:
return (pkt->s.ndntlv.interestlifetime / 1000);
#endif
default:
break;
}
return CCNL_INTEREST_TIMEOUT;
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-android/native/include/ccn-lite-android.h | <filename>src/ccnl-android/native/include/ccn-lite-android.h
/*
* @f ccn-lite-android.h
* @b native code (library) for Android devices
*
* Copyright (C) 2017, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCN_LITE_ANDROID
#define CCN_LITE_ANDROID
#include "ccn-lite-jni.h"
#include <dirent.h>
#include <fnmatch.h>
#include <jni.h>
#include <pthread.h>
#include <regex.h>
#include <arpa/inet.h>
#include <linux/if.h>
#include <linux/in.h>
#include <linux/sockios.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <android/looper.h>
#include "ccnl-pkt-ccnb.h"
#include "ccnl-pkt-ccntlv.h"
#include "ccnl-pkt-ndntlv.h"
#include "ccnl-pkt-switch.h"
#include "ccnl-dispatch.h"
void append_to_log(char *line);
int
ccnl_open_udpdev(int port, struct sockaddr_in *si);
void
ccnl_ll_TX(struct ccnl_relay_s *ccnl, struct ccnl_if_s *ifc,
sockunion *dest, struct ccnl_buf_s *buf);
int
ccnl_close_socket(int s);
void ccnl_ageing(void *relay, void *aux);
void
add_udpPort(struct ccnl_relay_s *relay, int port);
void
ccnl_relay_config(struct ccnl_relay_s *relay, int httpport, char *uxpath,
int max_cache_entries, char *crypto_face_path);
void
ccnl_populate_cache(struct ccnl_relay_s *ccnl, char *path);
int
ccnl_android_timer_io(int fd, int events, void *data);
int
ccnl_android_udp_io(int fd, int events, void *data);
int
ccnl_android_http_io(int fd, int events, void *data);
int
ccnl_android_http_accept(int fd, int events, void *data);
void*
timer();
char*
ccnl_android_init();
char*
ccnl_android_getTransport();
#endif //CCN_LITE_ANDROID
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/src/ccnl-pkt.c | <reponame>azadeh-afzar/CCN-IRIBU<gh_stars>10-100
/*
* @f ccnl-pkt.c
* @b CCN lite, core CCNx protocol logic
*
* Copyright (C) 2011-18 University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_LINUXKERNEL
#include "ccnl-pkt.h"
#include "ccnl-os-time.h"
#include "ccnl-defs.h"
#include "ccnl-pkt-ccntlv.h"
#include "ccnl-prefix.h"
#include "ccnl-malloc.h"
#include "ccnl-logging.h"
#else
#include "../include/ccnl-pkt.h"
#include "../include/ccnl-os-time.h"
#include "../include/ccnl-defs.h"
#include "../../ccnl-pkt/include/ccnl-pkt-ccntlv.h"
#include "../include/ccnl-prefix.h"
#include "../include/ccnl-malloc.h"
#include "../include/ccnl-logging.h"
#endif
void
ccnl_pkt_free(struct ccnl_pkt_s *pkt)
{
if (pkt) {
if (pkt->pfx) {
switch (pkt->pfx->suite) {
#ifdef USE_SUITE_CCNB
case CCNL_SUITE_CCNB:
ccnl_free(pkt->s.ccnb.nonce);
ccnl_free(pkt->s.ccnb.ppkd);
break;
#endif
#ifdef USE_SUITE_CCNTLV
case CCNL_SUITE_CCNTLV:
ccnl_free(pkt->s.ccntlv.keyid);
break;
#endif
#ifdef USE_SUITE_NDNTLV
case CCNL_SUITE_NDNTLV:
ccnl_free(pkt->s.ndntlv.nonce);
ccnl_free(pkt->s.ndntlv.ppkl);
break;
#endif
#ifdef USE_SUITE_LOCALRPC
case CCNL_SUITE_LOCALRPC:
#endif
default:
break;
}
ccnl_prefix_free(pkt->pfx);
}
if(pkt->buf){
ccnl_free(pkt->buf);
}
ccnl_free(pkt);
}
}
struct ccnl_pkt_s *
ccnl_pkt_dup(struct ccnl_pkt_s *pkt){
struct ccnl_pkt_s * ret = ccnl_malloc(sizeof(struct ccnl_pkt_s));
if(!pkt){
if (ret) {
ccnl_free(ret);
}
return NULL;
}
if(!ret){
return NULL;
}
if (pkt->pfx) {
ret->s = pkt->s;
switch (pkt->pfx->suite) {
#ifdef USE_SUITE_CCNB
case CCNL_SUITE_CCNB:
ret->s.ccnb.nonce = buf_dup(pkt->s.ccnb.nonce);
ret->s.ccnb.ppkd = buf_dup(pkt->s.ccnb.ppkd);
break;
#endif
#ifdef USE_SUITE_CCNTLV
case CCNL_SUITE_CCNTLV:
ret->s.ccntlv.keyid = buf_dup(pkt->s.ccntlv.keyid);
break;
#endif
#ifdef USE_SUITE_NDNTLV
case CCNL_SUITE_NDNTLV:
ret->s.ndntlv.nonce = buf_dup(pkt->s.ndntlv.nonce);
ret->s.ndntlv.ppkl = buf_dup(pkt->s.ndntlv.ppkl);
break;
#endif
#ifdef USE_SUITE_LOCALRPC
case CCNL_SUITE_LOCALRPC:
#endif
default:
break;
}
ret->pfx = ccnl_prefix_dup(pkt->pfx);
if(!ret->pfx){
ret->buf = NULL;
ccnl_pkt_free(ret);
return NULL;
}
ret->pfx->suite = pkt->pfx->suite;
ret->suite = pkt->suite;
ret->buf = buf_dup(pkt->buf);
ret->content = ret->buf->data + (pkt->content - pkt->buf->data);
ret->contlen = pkt->contlen;
}
return ret;
}
size_t
ccnl_pkt_mkComponent(int suite, uint8_t *dst, char *src, size_t srclen)
{
size_t len = 0;
switch (suite) {
#ifdef USE_SUITE_CCNTLV
case CCNL_SUITE_CCNTLV: {
if (srclen > UINT16_MAX) {
return 0;
}
uint16_t *sp = (uint16_t*) dst;
*sp++ = htons(CCNX_TLV_N_NameSegment);
len = srclen;
*sp++ = htons((uint16_t) len);
memcpy(sp, src, len);
len += 2*sizeof(uint16_t);
break;
}
#endif
default:
len = srclen;
memcpy(dst, src, len);
break;
}
return len;
}
int
ccnl_pkt_prependComponent(int suite, char *src, int *offset, unsigned char *buf)
{
int len = strlen(src);
DEBUGMSG_CUTL(TRACE, "ccnl_pkt_prependComponent(%d, %s)\n", suite, src);
if (*offset < len)
return -1;
memcpy(buf + *offset - len, src, len);
*offset -= len;
#ifdef USE_SUITE_CCNTLV
if (suite == CCNL_SUITE_CCNTLV) {
unsigned short *sp = (unsigned short*) (buf + *offset) - 1;
if (*offset < 4)
return -1;
*sp-- = htons(len);
*sp = htons(CCNX_TLV_N_NameSegment);
len += 2*sizeof(unsigned short);
*offset -= 2*sizeof(unsigned short);
}
#endif
return len;
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-utils/src/ccn-lite-ccnb2xml.c | /*
* @f util/ccn-lite-ccnb2xml.c
* @b pretty print CCNB content to XML
*
* Copyright (C) 2013, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2012-07-01 created
*/
#include "ccnl-common.h"
#include "ccnl-crypto.h"
// ----------------------------------------------------------------------
#define MAX_DEPTH 30
const char*
dtag2str(uint64_t dtag)
{
switch (dtag) {
// Try DTAGs defined in ccnl-pkt-ccnb.h
case CCN_DTAG_ANY: return "ANY";
case CCN_DTAG_NAME: return "NAME";
case CCN_DTAG_COMPONENT: return "COMPONENT";
case CCN_DTAG_CERTIFICATE: return "CERTIFICATE";
case CCN_DTAG_CONTENT: return "CONTENT";
case CCN_DTAG_SIGNEDINFO: return "SIGNEDINFO";
case CCN_DTAG_CONTENTDIGEST: return "CONTENTDIGEST";
case CCN_DTAG_INTEREST: return "INTEREST";
case CCN_DTAG_KEY: return "KEY";
case CCN_DTAG_KEYLOCATOR: return "KEYLOCATOR";
case CCN_DTAG_KEYNAME: return "KEYNAME";
case CCN_DTAG_SIGNATURE: return "SIGNATURE";
case CCN_DTAG_TIMESTAMP: return "TIMESTAMP";
case CCN_DTAG_TYPE: return "TYPE";
case CCN_DTAG_NONCE: return "NONCE";
case CCN_DTAG_SCOPE: return "SCOPE";
case CCN_DTAG_EXCLUDE: return "EXCLUDE";
case CCN_DTAG_ANSWERORIGKIND: return "ANSWERORIGKIND";
case CCN_DTAG_WITNESS: return "WITNESS";
case CCN_DTAG_SIGNATUREBITS: return "SIGNATUREBITS";
case CCN_DTAG_DIGESTALGO: return "DIGESTALGO";
case CCN_DTAG_FRESHNESS: return "FRESHNESS";
case CCN_DTAG_FINALBLOCKID: return "FINALBLOCKID";
case CCN_DTAG_PUBPUBKDIGEST: return "PUBPUBKDIGEST";
case CCN_DTAG_PUBCERTDIGEST: return "PUBCERTDIGEST";
case CCN_DTAG_CONTENTOBJ: return "CONTENTOBJ";
case CCN_DTAG_ACTION: return "ACTION";
case CCN_DTAG_FACEID: return "FACEID";
case CCN_DTAG_IPPROTO: return "IPPROTO";
case CCN_DTAG_HOST: return "HOST";
case CCN_DTAG_PORT: return "PORT";
case CCN_DTAG_FWDINGFLAGS: return "FWDINGFLAGS";
case CCN_DTAG_FACEINSTANCE: return "FACEINSTANCE";
case CCN_DTAG_FWDINGENTRY: return "FWDINGENTRY";
case CCN_DTAG_MINSUFFCOMP: return "MINSUFFCOMP";
case CCN_DTAG_MAXSUFFCOMP: return "MAXSUFFCOMP";
case CCN_DTAG_SEQNO: return "SEQNO";
case CCN_DTAG_FragA: return "FragA";
case CCN_DTAG_FragB: return "FragB";
case CCN_DTAG_FragC: return "FragC";
case CCN_DTAG_FragD: return "FragD";
case CCN_DTAG_FragP: return "FragP";
case CCN_DTAG_CCNPDU: return "CCNPDU";
// Try DTAGs defined in ccnl-defs.h
case CCNL_DTAG_MACSRC: return "MACSRC";
case CCNL_DTAG_IP4SRC: return "IP4SRC";
case CCNL_DTAG_IP6SRC: return "IP6SRC";
case CCNL_DTAG_UNIXSRC: return "UNIXSRC";
case CCNL_DTAG_FRAG: return "FRAG";
case CCNL_DTAG_FACEFLAGS: return "FACEFLAGS";
case CCNL_DTAG_DEVINSTANCE: return "DEVINSTANCE";
case CCNL_DTAG_DEVNAME: return "DEVNAME";
case CCNL_DTAG_DEVFLAGS: return "DEVFLAGS";
case CCNL_DTAG_MTU: return "MTU";
case CCNL_DTAG_DEBUGREQUEST: return "DEBUGREQUEST";
case CCNL_DTAG_DEBUGACTION: return "DEBUGACTION";
case CCNL_DTAG_DEBUGREPLY: return "DEBUGREPLY";
case CCNL_DTAG_INTERFACE: return "INTERFACE";
case CCNL_DTAG_NEXT: return "NEXT";
case CCNL_DTAG_PREV: return "PREV";
case CCNL_DTAG_IFNDX: return "IFNDX";
case CCNL_DTAG_IP: return "IP";
case CCNL_DTAG_ETH: return "ETH";
case CCNL_DTAG_UNIX: return "UNIX";
case CCNL_DTAG_PEER: return "PEER";
case CCNL_DTAG_FWD: return "FWD";
case CCNL_DTAG_FACE: return "FACE";
case CCNL_DTAG_ADDRESS: return "ADDRESS";
case CCNL_DTAG_SOCK: return "SOCK";
case CCNL_DTAG_REFLECT: return "REFLECT";
case CCNL_DTAG_PREFIX: return "PREFIX";
case CCNL_DTAG_INTERESTPTR: return "INTERESTPTR";
case CCNL_DTAG_LAST: return "LAST";
case CCNL_DTAG_MIN: return "MIN";
case CCNL_DTAG_MAX: return "MAX";
case CCNL_DTAG_RETRIES: return "RETRIES";
case CCNL_DTAG_PUBLISHER: return "PUBLISHER";
case CCNL_DTAG_CONTENTPTR: return "CONTENTPTR";
case CCNL_DTAG_LASTUSE: return "LASTUSE";
case CCNL_DTAG_SERVEDCTN: return "SERVEDCTN";
case CCNL_DTAG_VERIFIED: return "VERIFIED";
case CCNL_DTAG_CALLBACK: return "CALLBACK";
case CCNL_DTAG_SUITE: return "SUITE";
case CCNL_DTAG_COMPLENGTH: return "COMPLENGTH";
}
// DEBUGMSG(WARNING, "DTAG '%d' is missing in %s of %s:%d\n", dtag, __func__, __FILE__, __LINE__);
return "?";
}
const char*
tag2str(uint64_t tag, uint64_t num)
{
switch (tag) {
case CCN_TT_TAG: return "TAG";
case CCN_TT_DTAG: return dtag2str(num);
case CCN_TT_ATTR: return "ATTR";
case CCN_TT_DATTR: return "DATTR";
case CCN_TT_BLOB: return "BLOB";
case CCN_TT_UDATA: return "UDATA";
}
// DEBUGMSG(WARNING, "CCN_TT tag '%d' is missing in %s of %s:%d\n", tag, __func__, __FILE__, __LINE__);
return "?";
}
int8_t
is_ccn_tt(uint64_t tag, uint64_t num)
{
return strcmp("?", tag2str(tag, num)) != 0;
}
int8_t
is_ccn_blob(uint64_t tag)
{
return tag == CCN_TT_BLOB || tag == CCN_TT_UDATA;
}
int8_t
lookahead(uint8_t **buf, size_t *len, uint64_t *num, uint8_t *typ, uint8_t ignoreBlobTag, int depth)
{
int8_t rc, rc2;
uint64_t look_num;
uint8_t look_typ;
uint8_t *old_buf = *buf;
size_t old_len = *len;
if (depth > MAX_DEPTH) {
return 0;
}
rc = ccnl_ccnb_dehead(buf, len, num, typ);
if (ignoreBlobTag && rc == 0 && is_ccn_blob(*typ)) {
rc2 = ccnl_ccnb_dehead(buf, len, &look_num, &look_typ);
if (rc2 == 0 && is_ccn_tt(look_typ, look_num)) {
*num = look_num;
*typ = look_typ;
rc = rc2;
}
}
*buf = old_buf;
*len = old_len;
return rc;
}
int8_t
dehead(uint8_t **buf, size_t *len, uint64_t *num, uint8_t *typ, uint8_t ignoreBlobTag, int depth)
{
uint64_t look_num;
uint8_t look_typ;
int8_t rc_dehead, rc_lookahead;
if (depth > MAX_DEPTH){
return 0;
}
rc_dehead = ccnl_ccnb_dehead(buf, len, num, typ);
if (ignoreBlobTag && rc_dehead == 0 && is_ccn_blob(*typ)) {
rc_lookahead = lookahead(buf, len, &look_num, &look_typ, ignoreBlobTag, depth+1);
if (rc_lookahead == 0 && is_ccn_tt(look_typ, look_num)) {
// If we found BLOB data and inside there is a valid tag, just ignore BLOB and advance
return dehead(buf, len, num, typ, ignoreBlobTag, depth+1);
}
}
return rc_dehead;
}
void
print_offset(size_t offset)
{
size_t i;
for (i = 0; i < offset; ++i) {
printf(" ");
}
}
void
print_value(size_t offset, uint8_t *valptr, size_t vallen, int depth)
{
if (depth > MAX_DEPTH){
return;
}
size_t i;
(void)offset;
if (vallen == 1 && ccnl_isSuite(valptr[0])) {
printf("%u", valptr[0]);
} else {
for (i = 0; i < vallen; ++i) {
printf("%c", valptr[i]);
}
}
}
void
print_tag(size_t offset, uint64_t typ, uint64_t num, uint8_t openTag, uint8_t withNewlines, int depth)
{
if (depth > MAX_DEPTH){
return;
}
if (openTag || withNewlines) {
print_offset(offset);
}
printf("<");
if (!openTag) {
printf("/");
}
printf("%s", tag2str(typ, num));
printf(">");
if (!openTag || withNewlines) {
printf("\n");
}
}
void
print_blob(uint8_t **buf, size_t *len, uint8_t typ, uint64_t num, size_t offset, uint8_t ignoreBlobTag, int depth)
{
size_t vallen;
uint8_t *valptr;
if (depth > MAX_DEPTH){
return;
}
if (!ignoreBlobTag) {
print_tag(offset, typ, num, true, false, depth+1);
}
ccnl_ccnb_consume(typ, num, buf, len, &valptr, &vallen);
if (vallen > *len) {
return;
}
print_value(offset, valptr, vallen, depth+1);
if (!ignoreBlobTag) {
print_tag(offset, typ, num, false, false, depth+1);
}
}
void
print_ccnb(uint8_t **buf, size_t *len, size_t offset, uint8_t ignoreBlobTag, int depth)
{
uint64_t num, look_num;
uint8_t typ, look_typ;
int8_t rc;
if (depth > MAX_DEPTH) {
return;
}
while (dehead(buf, len, &num, &typ, ignoreBlobTag, depth+1) == 0) {
if (num == 0 && typ == 0) {
break;
}
rc = lookahead(buf, len, &look_num, &look_typ, ignoreBlobTag, depth+1);
if (is_ccn_blob(typ) && (rc != 0 || !is_ccn_tt(look_typ, look_num))) {
print_blob(buf, len, typ, num, offset, ignoreBlobTag, depth+1);
}
else {
uint8_t withNewlines = true;
if (ignoreBlobTag && rc == 0 && is_ccn_blob(look_typ)) {
withNewlines = false;
}
print_tag(offset, typ, num, true, withNewlines, depth+1);
print_ccnb(buf, len, offset+4, ignoreBlobTag, depth+1);
print_tag(offset, typ, num, false, withNewlines, depth+1);
}
}
}
int
main(int argc, char *argv[])
{
unsigned char out[64000];
unsigned char *p_out;
size_t len;
ssize_t len_s;
int opt;
uint8_t ignoreBlobTag = true;
while ((opt = getopt(argc, argv, "hb")) != -1) {
switch (opt) {
case 'b':
ignoreBlobTag = false;
break;
case 'h':
default:
fprintf(stderr, "usage: %s [option]\n"
"Parses ccn-lite-ctrl/ccnl-ext-mgmt messages (CCNB) and shows them in XML format.\n"
" -b include blob tags in the XML tree\n"
" -h print this message\n"
, argv[0]);
exit(-1);
}
}
len_s = read(0, out, sizeof(out));
if (len_s < 0) {
perror("read");
exit(-1);
}
len = (size_t) len_s;
p_out = out;
print_ccnb(&p_out, &len, 0, ignoreBlobTag, 0);
return 0;
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-android/native/include/ccn-lite-jni.h | <reponame>azadeh-afzar/CCN-IRIBU
#include <string.h>
#include <jni.h>
#ifndef CCN_LITE_JNI
#define CCN_LITE_JNI
static JavaVM *jvm;
static jclass ccnLiteClass;
static jobject ccnLiteObject;
#include "ccnl-core.h"
int jni_bleSend(unsigned char *data, int len);
JNIEXPORT jstring JNICALL
Java_ch_unibas_ccn_1lite_1android_CcnLiteAndroid_relayInit(JNIEnv* env,
jobject thiz);
JNIEXPORT jstring JNICALL
Java_ch_unibas_ccn_1lite_1android_CcnLiteAndroid_relayGetTransport(JNIEnv* env,
jobject thiz);
char*
lvl2str(int level);
JNIEXPORT jstring JNICALL
Java_ch_unibas_ccn_1lite_1android_CcnLiteAndroid_relayPlus(JNIEnv* env,
jobject thiz);
JNIEXPORT jstring JNICALL
Java_ch_unibas_ccn_1lite_1android_CcnLiteAndroid_relayMinus(JNIEnv* env,
jobject thiz);
JNIEXPORT void JNICALL
Java_ch_unibas_ccn_1lite_1android_CcnLiteAndroid_relayDump(JNIEnv* env,
jobject thiz);
JNIEXPORT void JNICALL
Java_ch_unibas_ccn_1lite_1android_CcnLiteAndroid_relayTimer(JNIEnv* env,
jobject thiz);
void
add_route(char *pfx, struct ccnl_face_s *face, int suite, int mtu);
JNIEXPORT void JNICALL
Java_ch_unibas_ccn_1lite_1android_CcnLiteAndroid_relayRX(JNIEnv* env,
jobject thiz,
jbyteArray addr,
jbyteArray data);
void jni_append_to_log(char *line);
int jni_bleSend(unsigned char *data, int len);
#endif //CCN_LITE_JNI
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-frag.h | /*
* @f ccnl-frag.h
* @b CCN lite (CCNL), core header file (internal data structures)
*
* Copyright (C) 2011-17, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_FRAG_H
#define CCNL_FRAG_H
#include "ccnl-sockunion.h"
#include "ccnl-face.h"
#include "ccnl-relay.h"
// returns >=0 if content consumed, buf and len pointers updated
typedef int (RX_datagram)(struct ccnl_relay_s*, struct ccnl_face_s*,
unsigned char**, int*);
struct ccnl_frag_s {
int protocol; // fragmentation protocol, 0=none
int mtu;
sockunion dest;
struct ccnl_buf_s *bigpkt; // outgoing bytes
unsigned int sendoffs;
int outsuite; // suite of outgoing packet
// transport state, if present:
int ifndx;
// int insuite; // suite of incoming packet series
struct ccnl_buf_s *defrag; // incoming bytes
unsigned int sendseq;
unsigned int losscount;
unsigned int recvseq;
unsigned char flagwidth;
unsigned char sendseqwidth;
unsigned char losscountwidth;
unsigned char recvseqwidth;
};
struct serialFragPDU_s { // collect all fields of a numbered HBH fragment
int contlen;
unsigned char *content;
unsigned int flags, ourseq, ourloss, yourseq, HAS;
unsigned char flagwidth, ourseqwidth, ourlosswidth, yourseqwidth;
};
struct ccnl_frag_s*
ccnl_frag_new(int protocol, int mtu);
void
ccnl_frag_reset(struct ccnl_frag_s *e, struct ccnl_buf_s *buf,
int ifndx, sockunion *dst);
int
ccnl_frag_getfragcount(struct ccnl_frag_s *e, int origlen, int *totallen);
#ifdef OBSOLTE_BY_2015_06
#ifdef USE_SUITE_CCNB
struct ccnl_buf_s*
ccnl_frag_getnextSEQD2012(struct ccnl_frag_s *e, int *ifndx, sockunion *su);
struct ccnl_buf_s*
ccnl_frag_getnextCCNx2013(struct ccnl_frag_s *fr, int *ifndx, sockunion *su);
#endif // USE_SUITE_CCNB
struct ccnl_buf_s*
ccnl_frag_getnextSEQD2015(struct ccnl_frag_s *fr, int *ifndx, sockunion *su);
#endif // OBSOLTE_BY_2015_06
struct ccnl_buf_s*
ccnl_frag_getnextBE2015(struct ccnl_frag_s *fr, int *ifndx, sockunion *su);
struct ccnl_buf_s*
ccnl_frag_getnext(struct ccnl_frag_s *fr, int *ifndx, sockunion *su);
int
ccnl_frag_nomorefragments(struct ccnl_frag_s *e);
void
ccnl_frag_destroy(struct ccnl_frag_s *e);
void
serialFragPDU_init(struct serialFragPDU_s *s);
#ifdef OBSOLETE_BY_2015_06
// processes a SEQENCED fragment. Once fully assembled we call the callback
void
ccnl_frag_RX_serialfragment(RX_datagram callback,
struct ccnl_relay_s *relay,
struct ccnl_face_s *from,
struct serialFragPDU_s *s)
#ifdef USE_SUITE_CCNB
#define getNumField(var,len,flag,rem) \
DEBUGMSG_EFRA(TRACE, " parsing " rem "\n"); \
if (ccnl_ccnb_unmkBinaryInt(data, datalen, &var, &len) != 0) \
goto Bail; \
s.HAS |= flag
#define HAS_FLAGS 0x01
#define HAS_OSEQ 0x02
#define HAS_OLOS 0x04
#define HAS_YSEQ 0x08
int
ccnl_frag_RX_frag2012(RX_datagram callback,
struct ccnl_relay_s *relay, struct ccnl_face_s *from,
unsigned char **data, int *datalen);
int
ccnl_frag_RX_CCNx2013(RX_datagram callback,
struct ccnl_relay_s *relay, struct ccnl_face_s *from,
unsigned char **data, int *datalen);
#endif USE_SUITE_CCNB
int
ccnl_frag_RX_Sequenced2015(RX_datagram callback, struct ccnl_relay_s *relay,
struct ccnl_face_s *from, int mtu,
unsigned int bits, unsigned int seqno,
unsigned char **data, int *datalen);
#endif // OBSOLTE_BY_2015_06
int
ccnl_frag_RX_BeginEnd2015(RX_datagram callback, struct ccnl_relay_s *relay,
struct ccnl_face_s *from, int mtu,
unsigned int bits, unsigned int seqno,
unsigned char **data, int *datalen);
struct ccnl_buf_s*
ccnl_frag_getnext(struct ccnl_frag_s *fr, int *ifndx, sockunion *su);
#endif //CCNL_FRAG_H
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/src/ccnl-content.c | <gh_stars>10-100
/*
* @f ccnl-content.c
* @b CCN lite, core CCNx protocol logic
*
* Copyright (C) 2011-18 University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_LINUXKERNEL
#include "ccnl-content.h"
#include "ccnl-malloc.h"
#include "ccnl-prefix.h"
#include "ccnl-pkt.h"
#include "ccnl-os-time.h"
#include "ccnl-logging.h"
#include "ccnl-defs.h"
#else
#include "../include/ccnl-content.h"
#include "../include/ccnl-malloc.h"
#include "../include/ccnl-prefix.h"
#include "../include/ccnl-pkt.h"
#include "../include/ccnl-os-time.h"
#include "../include/ccnl-logging.h"
#endif
// TODO: remove unused ccnl parameter
struct ccnl_content_s*
ccnl_content_new(struct ccnl_pkt_s **pkt)
{
if (!pkt) {
return NULL;
}
struct ccnl_content_s *c;
char s[CCNL_MAX_PREFIX_SIZE];
(void) s;
DEBUGMSG_CORE(TRACE, "ccnl_content_new %p <%s [%lu]>\n",
(void*) *pkt, ccnl_prefix_to_str((*pkt)->pfx, s, CCNL_MAX_PREFIX_SIZE),
((*pkt)->pfx->chunknum) ? (long unsigned) *((*pkt)->pfx->chunknum) : (long unsigned) 0);
c = (struct ccnl_content_s *) ccnl_calloc(1, sizeof(struct ccnl_content_s));
if (!c)
return NULL;
c->pkt = *pkt;
*pkt = NULL;
c->last_used = CCNL_NOW();
c->flags = CCNL_CONTENT_FLAGS_NOT_STALE;
return c;
}
int
ccnl_content_free(struct ccnl_content_s *content)
{
if (content) {
if (content->pkt) {
ccnl_pkt_free(content->pkt);
}
ccnl_free(content);
return 0;
}
return -1;
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-pkt/src/ccnl-pkt-ccntlv.c | <filename>src/ccnl-pkt/src/ccnl-pkt-ccntlv.c
/*
* @f pkt-ccntlv.c
* @b CCN lite - CCNx pkt parsing and composing (TLV pkt format Sep 22, 2014)
*
* Copyright (C) 2014-15, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2014-03-05 created
* 2014-11-05 merged from pkt-ccntlv-enc.c pkt-ccntlv-dec.c
*/
#ifdef USE_SUITE_CCNTLV
#ifndef CCNL_LINUXKERNEL
#include "ccnl-pkt-ccntlv.h"
#include "ccnl-core.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <assert.h>
#else
#include "../include/ccnl-pkt-ccntlv.h"
#include "../../ccnl-core/include/ccnl-core.h"
#endif
#ifndef DEBUGMSG_PCNX
# define DEBUGMSG_PCNX(...) DEBUGMSG(__VA_ARGS__)
#endif
/* ----------------------------------------------------------------------
Note:
For a CCNTLV prefix, we store the name components INCLUDING
the TL. This is different for CCNB and NDNTLV where we only keep
a component's value bytes, as there is only one "type" of name
component.
This might change in the future (on the side of CCNB and NDNTLV prefixes).
*/
// ----------------------------------------------------------------------
// packet decomposition
// convert network order byte array into local unsigned integer value
int8_t
ccnl_ccnltv_extractNetworkVarInt(uint8_t *buf, size_t len,
uint32_t *intval)
{
uint32_t val = 0;
if (len > sizeof(uint32_t)) {
return -1;
}
while (len-- > 0) {
val = (val << 8U) | *buf;
buf++;
}
*intval = val;
return 0;
}
// returns hdr length to skip before the payload starts.
// this value depends on the type (interest/data/nack) and opt headers
// but should be available in the fixed header
int8_t
ccnl_ccntlv_getHdrLen(uint8_t *data, size_t datalen, size_t *hdrlen)
{
struct ccnx_tlvhdr_ccnx2015_s *hp;
hp = (struct ccnx_tlvhdr_ccnx2015_s*) data;
if (datalen >= hp->hdrlen) {
*hdrlen = hp->hdrlen;
return 0;
}
return -1;
}
int8_t
ccnl_ccntlv_dehead(uint8_t **buf, size_t *len,
uint16_t *typ, size_t *vallen)
{
size_t maxlen = *len;
if (*len < 4) { //ensure that len is not negative!
return -1;
}
*typ = ((*buf)[0] << 8U) | (*buf)[1];
*vallen = ((*buf)[2] << 8U) | (*buf)[3];
*len -= 4;
*buf += 4;
if (*vallen > maxlen) {
return -1; //Return failure (-1) if length value in the tlv is longer than the buffer
}
return 0;
}
// We use one extraction procedure for both interest and data pkts.
// This proc assumes that the packet header was already processed and consumed
struct ccnl_pkt_s*
ccnl_ccntlv_bytes2pkt(uint8_t *start, uint8_t **data, size_t *datalen)
{
struct ccnl_pkt_s *pkt;
struct ccnl_prefix_s *p;
uint32_t i;
size_t len;
size_t oldpos;
uint16_t typ;
#ifdef USE_HMAC256
uint8_t validAlgoIsHmac256 = 0;
#endif
DEBUGMSG_PCNX(TRACE, "ccnl_ccntlv_bytes2pkt len=%zu\n", *datalen);
pkt = (struct ccnl_pkt_s*) ccnl_calloc(1, sizeof(*pkt));
if (!pkt) {
return NULL;
}
pkt->pfx = p = ccnl_prefix_new(CCNL_SUITE_CCNTLV, CCNL_MAX_NAME_COMP);
if (!p) {
ccnl_free(pkt);
return NULL;
}
p->compcnt = 0;
#ifdef USE_HMAC256
pkt->hmacStart = *data;
#endif
// We ignore the TL types of the message for now:
// content and interests are filled in both cases (and only one exists).
// Validation info is now collected
if (ccnl_ccntlv_dehead(data, datalen, &typ, &len) || len > *datalen) {
goto Bail;
}
pkt->type = typ;
pkt->suite = CCNL_SUITE_CCNTLV;
pkt->val.final_block_id = -1;
// XXX this parsing is not safe for all input data - needs more bound
// checks, as some packets with wrong L values can bring this to crash
oldpos = *data - start;
while (ccnl_ccntlv_dehead(data, datalen, &typ, &len) == 0) {
uint8_t *cp = *data, *cp2;
size_t len2 = len;
size_t len3;
if (len > *datalen) {
goto Bail;
}
switch (typ) {
case CCNX_TLV_M_Name:
p->nameptr = start + oldpos;
while (len2 > 0) {
cp2 = cp;
if (ccnl_ccntlv_dehead(&cp, &len2, &typ, &len3) || len>*datalen) {
goto Bail;
}
switch (typ) {
case CCNX_TLV_N_Chunk:
// We extract the chunknum to the prefix but keep it
// in the name component for now. In the future we
// possibly want to remove the chunk segment from the
// name components and rely on the chunknum field in
// the prefix.
p->chunknum = (uint32_t *) ccnl_malloc(sizeof(uint32_t));
if (ccnl_ccnltv_extractNetworkVarInt(cp, len3, p->chunknum) < 0) {
DEBUGMSG_PCNX(WARNING, "Error in NetworkVarInt for chunk\n");
goto Bail;
}
if (p->compcnt < CCNL_MAX_NAME_COMP) {
p->comp[p->compcnt] = cp2;
p->complen[p->compcnt] = cp - cp2 + len3;
p->compcnt++;
} // else out of name component memory: skip
break;
case CCNX_TLV_N_NameSegment:
if (p->compcnt < CCNL_MAX_NAME_COMP) {
p->comp[p->compcnt] = cp2;
p->complen[p->compcnt] = cp - cp2 + len3;
p->compcnt++;
} // else out of name component memory: skip
break;
case CCNX_TLV_N_Meta:
if (ccnl_ccntlv_dehead(&cp, &len2, &typ, &len3) || len > *datalen) {
DEBUGMSG_PCNX(WARNING, "error when extracting CCNX_TLV_M_MetaData\n");
goto Bail;
}
break;
default:
break;
}
cp += len3;
len2 -= len3;
}
p->namelen = *data - p->nameptr;
break;
case CCNX_TLV_M_ENDChunk: {
uint32_t final_block_id;
if (ccnl_ccnltv_extractNetworkVarInt(cp, len, &final_block_id) < 0) {
DEBUGMSG_PCNX(WARNING, "error when extracting CCNX_TLV_M_ENDChunk\n");
goto Bail;
}
pkt->val.final_block_id = final_block_id;
break;
}
case CCNX_TLV_M_Payload:
pkt->content = *data;
pkt->contlen = len;
break;
#ifdef USE_HMAC256
case CCNX_TLV_TL_ValidationAlgo:
cp = *data;
len2 = len;
if (ccnl_ccntlv_dehead(&cp, &len2, &typ, &len3) || len > *datalen) {
goto Bail;
}
if (typ == CCNX_VALIDALGO_HMAC_SHA256) {
// ignore keyId and other algo dependent data ... && len3 == 0)
validAlgoIsHmac256 = 1;
}
break;
case CCNX_TLV_TL_ValidationPayload:
if (pkt->hmacStart && validAlgoIsHmac256 && len == 32) {
pkt->hmacLen = *data - pkt->hmacStart - 4;
pkt->hmacSignature = *data;
}
break;
#endif
default:
break;
}
*data += len;
*datalen -= len;
oldpos = *data - start;
}
if (*datalen > 0) {
goto Bail;
}
pkt->pfx = p;
pkt->buf = ccnl_buf_new(start, *data - start);
if (!pkt->buf) {
goto Bail;
}
// carefully rebase ptrs to new buf because of 64bit pointers:
if (pkt->content) {
pkt->content = pkt->buf->data + (pkt->content - start);
}
for (i = 0; i < p->compcnt; i++) {
p->comp[i] = pkt->buf->data + (p->comp[i] - start);
}
if (p->nameptr) {
p->nameptr = pkt->buf->data + (p->nameptr - start);
}
#ifdef USE_HMAC256
pkt->hmacStart = pkt->buf->data + (pkt->hmacStart - start);
pkt->hmacSignature = pkt->buf->data + (pkt->hmacSignature - start);
#endif
return pkt;
Bail:
ccnl_pkt_free(pkt);
return NULL;
}
// ----------------------------------------------------------------------
#ifdef NEEDS_PREFIX_MATCHING
// returns: 0=match, -1=otherwise
int8_t
ccnl_ccntlv_cMatch(struct ccnl_pkt_s *p, struct ccnl_content_s *c)
{
#ifndef CCNL_LINUXKERNEL
assert(p);
assert(p->suite == CCNL_SUITE_CCNTLV);
#endif
if (ccnl_prefix_cmp(c->pkt->pfx, NULL, p->pfx, CMP_EXACT)) {
return -1;
}
// TODO: check keyid
// TODO: check freshness, kind-of-reply
return 0;
}
#endif
// ----------------------------------------------------------------------
// packet composition
#ifdef NEEDS_PACKET_CRAFTING
// write given TL *before* position buf+offset, adjust offset and return len
int8_t
ccnl_ccntlv_prependTL(uint16_t type, size_t len,
size_t *offset, uint8_t *buf)
{
if (*offset < 4 || len > UINT16_MAX) {
return -1;
}
buf += *offset;
*offset -= 4;
*(buf-1) = (uint8_t) (len & 0xffU);
*(buf-2) = (uint8_t) (len & 0xff00U) >> 8U;
*(buf-3) = (uint8_t) (type & 0xffU);
*(buf-4) = (uint8_t) (type & 0xff00U) >> 8U;
return 0;
}
// write len bytes *before* position buf[offset], adjust offset
int8_t
ccnl_ccntlv_prependBlob(uint16_t type, uint8_t *blob,
size_t len, size_t *offset, uint8_t *buf)
{
if (*offset < (len + 4)) {
return -1;
}
*offset -= len;
memcpy(buf + *offset, blob, len);
if (ccnl_ccntlv_prependTL(type, len, offset, buf)) {
return -1;
}
return 0;
}
// write (in network order and with the minimal number of bytes)
// the given unsigned integer val *before* position buf[offset], adjust offset
// and return number of bytes prepended. 0 is represented as %x00
int8_t
ccnl_ccntlv_prependNetworkVarUInt(uint16_t type, uint32_t intval,
size_t *offset, uint8_t *buf)
{
size_t offs = *offset;
size_t len = 0;
while (offs > 0) {
buf[--offs] = (uint8_t) (intval & 0xffU);
len++;
intval = intval >> 8U;
if (!intval) {
break;
}
}
*offset = offs;
if (ccnl_ccntlv_prependTL(type, len, offset, buf)) {
return -1;
}
return 0;
}
#ifdef XXX
// write (in network order and with the minimal number of bytes)
// the given signed integer val *before* position buf[offset], adjust offset
// and return number of bytes prepended. 0 is represented as %x00
int
ccnl_ccntlv_prependNetworkVarSInt(unsigned short type, int intval,
int *offset, unsigned char *buf)
{
...
}
#endif
// write *before* position buf[offset] the CCNx1.0 fixed header,
// returns 0 on success, non-zero on failure.
int8_t
ccnl_ccntlv_prependFixedHdr(uint8_t ver,
uint8_t packettype,
size_t payloadlen,
uint8_t hoplimit,
size_t *offset, uint8_t *buf)
{
// optional headers are not yet supported, only the fixed header
uint8_t hdrlen = sizeof(struct ccnx_tlvhdr_ccnx2015_s);
size_t pktlen = hdrlen + payloadlen;
if (pktlen > UINT16_MAX) {
return -1;
}
struct ccnx_tlvhdr_ccnx2015_s *hp;
if (*offset < hdrlen) {
return -1;
}
*offset -= sizeof(struct ccnx_tlvhdr_ccnx2015_s);
hp = (struct ccnx_tlvhdr_ccnx2015_s *)(buf + *offset);
hp->version = ver;
hp->pkttype = packettype;
hp->hoplimit = hoplimit;
memset(hp->fill, 0, 2);
hp->hdrlen = hdrlen;
hp->pktlen = htons((uint16_t) pktlen);
return 0;
}
// write given prefix and chunknum *before* buf[offs], adjust offset.
// Returns 0 on success, non-zero on failure.
int8_t
ccnl_ccntlv_prependName(struct ccnl_prefix_s *name,
size_t *offset, uint8_t *buf,
const uint32_t *lastchunknum) {
size_t cnt;
size_t nameend;
if (lastchunknum) {
if (ccnl_ccntlv_prependNetworkVarUInt(CCNX_TLV_M_ENDChunk,
*lastchunknum, offset, buf)) {
return -1;
}
}
nameend = *offset;
if (name->chunknum &&
ccnl_ccntlv_prependNetworkVarUInt(CCNX_TLV_N_Chunk,
*name->chunknum, offset, buf)) {
return -1;
}
// optional: (not used)
// CCNX_TLV_N_Meta
for (cnt = name->compcnt; cnt > 0; cnt--) {
if (*offset < name->complen[cnt-1]) {
return -1;
}
*offset -= name->complen[cnt-1];
memcpy(buf + *offset, name->comp[cnt-1], name->complen[cnt-1]);
}
if (ccnl_ccntlv_prependTL(CCNX_TLV_M_Name, nameend - *offset,
offset, buf)) {
return -1;
}
return 0;
}
// write Interest payload *before* buf[offs], adjust offs and return bytes used
int8_t
ccnl_ccntlv_prependInterest(struct ccnl_prefix_s *name,
size_t *offset, uint8_t *buf, size_t *len)
{
size_t oldoffset = *offset;
if (ccnl_ccntlv_prependName(name, offset, buf, NULL)) {
return -1;
}
if (ccnl_ccntlv_prependTL(CCNX_TLV_TL_Interest,
oldoffset - *offset, offset, buf)) {
return -1;
}
*len = oldoffset - *offset;
return 0;
}
// write Interest packet *before* buf[offs], adjust offs and return bytes used
int8_t
ccnl_ccntlv_prependChunkInterestWithHdr(struct ccnl_prefix_s *name,
size_t *offset, uint8_t *buf, size_t *reslen)
{
size_t len, oldoffset;
uint8_t hoplimit = 64; // setting hoplimit to max valid value?
oldoffset = *offset;
if (ccnl_ccntlv_prependInterest(name, offset, buf, &len)) {
return -1;
}
if (len > (UINT16_MAX - sizeof(struct ccnx_tlvhdr_ccnx2015_s))) {
return -1;
}
if (ccnl_ccntlv_prependFixedHdr(CCNX_TLV_V1, CCNX_PT_Interest,
len, hoplimit, offset, buf)) {
return -1;
}
*reslen = oldoffset - *offset;
return 0;
}
// write Interest packet *before* buf[offs], adjust offs and return bytes used
int8_t
ccnl_ccntlv_prependInterestWithHdr(struct ccnl_prefix_s *name,
size_t *offset, uint8_t *buf, size_t *len)
{
return ccnl_ccntlv_prependChunkInterestWithHdr(name, offset, buf, len);
}
// write Content payload *before* buf[offs], adjust offs and return bytes used
int8_t
ccnl_ccntlv_prependContent(struct ccnl_prefix_s *name,
uint8_t *payload, size_t paylen,
uint32_t *lastchunknum, size_t *contentpos,
size_t *offset, uint8_t *buf, size_t *reslen)
{
size_t tloffset = *offset;
if (contentpos) {
*contentpos = *offset - paylen;
}
// fill in backwards
if (ccnl_ccntlv_prependBlob(CCNX_TLV_M_Payload, payload, paylen, offset, buf)) {
return -1;
}
if (ccnl_ccntlv_prependName(name, offset, buf, lastchunknum)) {
return -1;
}
if (ccnl_ccntlv_prependTL(CCNX_TLV_TL_Object, tloffset - *offset, offset, buf)) {
return -1;
}
*reslen = tloffset - *offset;
return 0;
}
// write Content packet *before* buf[offs], adjust offs and return bytes used
int8_t
ccnl_ccntlv_prependContentWithHdr(struct ccnl_prefix_s *name,
uint8_t *payload, size_t paylen,
uint32_t *lastchunknum, size_t *contentpos,
size_t *offset, uint8_t *buf, size_t *reslen)
{
size_t len, oldoffset;
uint8_t hoplimit = 255; // setting to max (content has no hoplimit)
oldoffset = *offset;
if (ccnl_ccntlv_prependContent(name, payload, paylen, lastchunknum,
contentpos, offset, buf, &len)) {
return -1;
}
if (len > (UINT16_MAX - sizeof(struct ccnx_tlvhdr_ccnx2015_s))) {
return -1;
}
if (ccnl_ccntlv_prependFixedHdr(CCNX_TLV_V1, CCNX_PT_Data,
len, hoplimit, offset, buf)) {
return -1;
}
*reslen = oldoffset - *offset;
return 0;
}
#ifdef USE_FRAG
// produces a full FRAG packet. It does not write, just read the fields in *fr
struct ccnl_buf_s*
ccnl_ccntlv_mkFrag(struct ccnl_frag_s *fr, unsigned int *consumed)
{
size_t datalen;
struct ccnl_buf_s *buf;
struct ccnx_tlvhdr_ccnx2015_s *fp;
uint16_t tmp;
DEBUGMSG_PCNX(TRACE, "ccnl_ccntlv_mkFrag seqno=%u\n", fr->sendseq);
datalen = fr->mtu - sizeof(*fp) - 4;
if (datalen > (fr->bigpkt->datalen - fr->sendoffs)) {
datalen = fr->bigpkt->datalen - fr->sendoffs;
}
if (datalen > UINT16_MAX) {
return NULL;
}
buf = ccnl_buf_new(NULL, sizeof(*fp) + 4 + datalen);
if (!buf) {
return NULL;
}
fp = (struct ccnx_tlvhdr_ccnx2015_s*) buf->data;
memset(fp, 0, sizeof(*fp));
fp->version = CCNX_TLV_V1;
fp->pkttype = CCNX_PT_Fragment;
fp->hdrlen = sizeof(*fp);
fp->pktlen = htons(sizeof(*fp) + 4 + datalen);
tmp = htons(CCNX_TLV_TL_Fragment);
memcpy(fp+1, &tmp, 2);
tmp = htons((uint16_t) datalen);
memcpy((char*)(fp+1) + 2, &tmp, 2);
memcpy((char*)(fp+1) + 4, fr->bigpkt->data + fr->sendoffs, datalen);
tmp = fr->sendseq & 0x03fff;
if (datalen >= fr->bigpkt->datalen) { // single
tmp |= CCNL_BEFRAG_FLAG_SINGLE << 14;
} else if (fr->sendoffs == 0) { // start
tmp |= CCNL_BEFRAG_FLAG_FIRST << 14;
} else if(datalen >= (fr->bigpkt->datalen - fr->sendoffs)) { // end
tmp |= CCNL_BEFRAG_FLAG_LAST << 14;
} else { // middle
tmp |= CCNL_BEFRAG_FLAG_MID << 14;
}
tmp = htons(tmp);
memcpy(fp->fill, &tmp, 2);
*consumed = datalen;
return buf;
}
#endif
#endif // NEEDS_PACKET_CRAFTING
#endif // USE_SUITE_CCNTLV
/* suppress empty translation unit error */
typedef int unused_typedef;
// eof
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/src/ccnl-logging.c | <gh_stars>10-100
/*
* @f ccnl-ext-logging.c
* @b CCNL logging
*
* Copyright (C) 2011-17, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created <<EMAIL>>
*/
#ifndef CCNL_LINUXKERNEL
#include "ccnl-logging.h"
#include <string.h>
#include <stdio.h>
#else
#include "../include/ccnl-logging.h"
#endif
int debug_level;
char
ccnl_debugLevelToChar(int level)
{
#if !defined(CCNL_ARDUINO) && !defined(CCNL_RIOT)
switch (level) {
case FATAL: return 'F';
case ERROR: return 'E';
case WARNING: return 'W';
case INFO: return 'I';
case DEBUG: return 'D';
case VERBOSE: return 'V';
case TRACE: return 'T';
default: return '?';
}
#else // gcc-avr creates a lookup table (in the data section) which
// we want to avoid. To force PROGMEM, we have to code :-(
if (level == FATAL)
return 'F';
if (level == ERROR)
return 'E';
if (level == WARNING)
return 'W';
if (level == INFO)
return 'I';
if (level == DEBUG)
return 'D';
if (level == VERBOSE)
return 'V';
if (level == TRACE)
return 'T';
return '?';
#endif
}
int
ccnl_debug_str2level(char *s)
{
if (!strcmp(s, "fatal")) return FATAL;
if (!strcmp(s, "error")) return ERROR;
if (!strcmp(s, "warning")) return WARNING;
if (!strcmp(s, "info")) return INFO;
if (!strcmp(s, "debug")) return DEBUG;
if (!strcmp(s, "trace")) return TRACE;
if (!strcmp(s, "verbose")) return VERBOSE;
return 1;
}
#ifdef USE_DEBUG
#ifdef USE_DEBUG_MALLOC
char *
getBaseName(char *fn)
{
char *cp = fn + strlen(fn);
for (cp--; cp >= fn; cp--)
if (*cp == '/')
break;
return cp+1;
}
void
debug_memdump(void)
{
struct mhdr *h;
CONSOLE("[M] %s: @@@ memory dump starts\n", timestamp());
for (h = mem; h; h = h->next) {
#ifdef CCNL_ARDUINO
sprintf_P(logstr, PSTR("addr %p %5d Bytes, "),
(int)((unsigned char *)h + sizeof(struct mhdr)),
h->size);
Serial.print(logstr);
// remove the "src/../" prefix:
strcpy_P(logstr, h->fname);
Serial.print(getBaseName(logstr));
CONSOLE(":%d @%d.%03d\n", h->lineno,
int(h->tstamp), int(1000*(h->tstamp - int(h->tstamp))));
#else
CONSOLE("addr %p %lu Bytes, %s:%d @%s\n",
(void *)(h + sizeof(struct mhdr)),
h->size, getBaseName(h->fname), h->lineno, h->tstamp);
#endif
}
CONSOLE("[M] %s: @@@ memory dump ends\n", timestamp());
}
#endif //USE_DEBUG_MALLOC
#endif //USE_DEBUG
|
azadeh-afzar/CCN-IRIBU | src/ccnl-pkt/include/ccnl-pkt-builder.h | <reponame>azadeh-afzar/CCN-IRIBU
/*
* @f ccnl-pkt-bilder.h
* @b CCN lite - CCN packet builder
*
* Copyright (C) 2011-17, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_PKT_BUILDER
#define CCNL_PKT_BUILDER
#ifndef CCNL_LINUXKERNEL
#include "ccnl-core.h"
#include "ccnl-pkt.h"
#include "ccnl-pkt-ccnb.h"
#include "ccnl-pkt-ccntlv.h"
#include "ccnl-pkt-ndntlv.h"
#include "ccnl-pkt-switch.h"
#include "ccnl-pkt-localrpc.h"
#else
#include "../../ccnl-core/include/ccnl-core.h"
#include "../../ccnl-core/include/ccnl-pkt.h"
#include "../include/ccnl-pkt-ccnb.h"
#include "../include/ccnl-pkt-ccntlv.h"
#include "../include/ccnl-pkt-ndntlv.h"
#include "../include/ccnl-pkt-switch.h"
#include "../include/ccnl-pkt-localrpc.h"
#endif
#ifdef USE_SUITE_CCNB
int8_t ccnb_isContent(uint8_t *buf, size_t len);
#endif // USE_SUITE_CCNB
#ifdef USE_SUITE_CCNTLV
struct ccnx_tlvhdr_ccnx2015_s*
ccntlv_isHeader(uint8_t *buf, size_t len);
int8_t ccntlv_isData(uint8_t *buf, size_t len);
int8_t ccntlv_isFragment(uint8_t *buf, size_t len);
#endif // USE_SUITE_CCNTLV
#ifdef USE_SUITE_NDNTLV
int8_t ndntlv_isData(uint8_t *buf, size_t len);
#endif //USE_SUITE_NDNTLV
int8_t
ccnl_isContent(uint8_t *buf, size_t len, int suite);
int8_t
ccnl_isFragment(uint8_t *buf, size_t len, int suite);
#ifdef NEEDS_PACKET_CRAFTING
struct ccnl_content_s *
ccnl_mkContentObject(struct ccnl_prefix_s *name,
uint8_t *payload, size_t paylen,
ccnl_data_opts_u *opts);
struct ccnl_buf_s*
ccnl_mkSimpleContent(struct ccnl_prefix_s *name,
uint8_t *payload, size_t paylen, size_t *payoffset,
ccnl_data_opts_u *opts);
int8_t
ccnl_mkContent(struct ccnl_prefix_s *name, uint8_t *payload, size_t paylen, uint8_t *tmp,
size_t *len, size_t *contentpos, size_t *offs, ccnl_data_opts_u *opts);
struct ccnl_interest_s *
ccnl_mkInterestObject(struct ccnl_prefix_s *name, ccnl_interest_opts_u *opts);
struct ccnl_buf_s*
ccnl_mkSimpleInterest(struct ccnl_prefix_s *name, ccnl_interest_opts_u *opts);
int8_t
ccnl_mkInterest(struct ccnl_prefix_s *name, ccnl_interest_opts_u *opts,
uint8_t *tmp, uint8_t *tmpend, size_t *len, size_t *offs);
#endif
#endif //CCNL_PKT_BUILDER
|
azadeh-afzar/CCN-IRIBU | src/ccnl-relay/ccn-lite-relay.c | <filename>src/ccnl-relay/ccn-lite-relay.c
/*
* @f ccn-lite-relay.c
* @b user space CCN relay
*
* Copyright (C) 2011-15, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2011-11-22 created
*/
#include <dirent.h>
#include <fnmatch.h>
#include <regex.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <inttypes.h>
#include <limits.h>
#ifdef USE_HTTP_STATUS
#include "ccnl-http-status.h"
#endif
#include "ccnl-os-includes.h"
#include "ccnl-core.h"
#include "ccnl-dispatch.h"
/*
#define CCNL_UNIX
#define USE_CCNxDIGEST
// #define USE_DEBUG // must select this for USE_MGMT
// #define USE_DEBUG_MALLOC
#define USE_DUP_CHECK
#define USE_ECHO
#define USE_LINKLAYER
//#define USE_FRAG
#define USE_HMAC256
#define USE_HTTP_STATUS
#define USE_IPV4
#define USE_IPV6
#define USE_MGMT
// #define USE_SCHEDULER
#define USE_STATS
#define USE_SUITE_CCNB // must select this for USE_MGMT
#define USE_SUITE_CCNTLV
#define USE_SUITE_NDNTLV
#define USE_SUITE_LOCALRPC
#define USE_UNIXSOCKET
// #define USE_SIGNATURES
#define NEEDS_PREFIX_MATCHING
*/
#include "ccn-lite-relay.h"
#include "ccnl-unix.h"
static int lasthour = -1;
static int inter_ccn_interval = 0; // in usec
static int inter_pkt_interval = 0; // in usec
#ifdef CCNL_ARDUINO
const char compile_string[] PROGMEM = ""
#else
const char *compile_string = ""
#endif
#ifdef USE_CCNxDIGEST
"CCNxDIGEST, "
#endif
#ifdef USE_DEBUG
"DEBUG, "
#endif
#ifdef USE_DEBUG_MALLOC
"DEBUG_MALLOC, "
#endif
#ifdef USE_ECHO
"ECHO, "
#endif
#ifdef USE_LINKLAYER
"ETHERNET, "
#endif
#ifdef USE_WPAN
"WPAN, "
#endif
#ifdef USE_FRAG
"FRAG, "
#endif
#ifdef USE_HMAC256
"HMAC256, "
#endif
#ifdef USE_HTTP_STATUS
"HTTP_STATUS, "
#endif
#ifdef USE_KITE
"KITE, "
#endif
#ifdef USE_LOGGING
"LOGGING, "
#endif
#ifdef USE_MGMT
"MGMT, "
#endif
#ifdef USE_SCHEDULER
"SCHEDULER, "
#endif
#ifdef USE_SIGNATURES
"SIGNATURES, "
#endif
#ifdef USE_SUITE_CCNB
"SUITE_CCNB, "
#endif
#ifdef USE_SUITE_CCNTLV
"SUITE_CCNTLV, "
#endif
#ifdef USE_SUITE_LOCALRPC
"SUITE_LOCALRPC, "
#endif
#ifdef USE_SUITE_NDNTLV
"SUITE_NDNTLV, "
#endif
#ifdef USE_UNIXSOCKET
"UNIXSOCKET, "
#endif
;
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
int
main(int argc, char **argv)
{
int opt, max_cache_entries = -1, httpport = -1;
int udpport1 = -1, udpport2 = -1;
int udp6port1 = -1, udp6port2 = -1;
char *datadir = NULL, *ethdev = NULL, *crypto_sock_path = NULL;
char *wpandev = NULL;
int suite = CCNL_SUITE_DEFAULT;
struct ccnl_relay_s *theRelay = ccnl_calloc(1, sizeof(struct ccnl_relay_s));
#ifdef USE_UNIXSOCKET
char *uxpath = CCNL_DEFAULT_UNIXSOCKNAME;
#else
char *uxpath = NULL;
#endif
#ifdef USE_ECHO
char *echopfx = NULL;
#endif
time(&theRelay->startup_time);
unsigned int seed = time(NULL) * getpid();
#ifdef __linux__
srand(seed);
#else
srandom(seed);
#endif
while ((opt = getopt(argc, argv, "hc:d:e:g:i:o:p:s:t:u:6:v:w:x:")) != -1) {
switch (opt) {
case 'c': {
long max_cache_entries_l;
errno = 0;
max_cache_entries_l = strtol(optarg, (char **) NULL, 10);
if (errno || max_cache_entries_l < INT_MIN || max_cache_entries_l > INT_MAX) {
goto usage;
}
max_cache_entries = (int) max_cache_entries_l;
break;
}
case 'd':
datadir = optarg;
break;
case 'e':
ethdev = optarg;
break;
case 'g': {
long inter_pkt_interval_l;
errno = 0;
inter_pkt_interval_l = strtol(optarg, (char **) NULL, 10);
if (errno || inter_pkt_interval_l < INT_MIN || inter_pkt_interval_l > INT_MAX) {
goto usage;
}
inter_pkt_interval = (int) inter_pkt_interval_l;
break;
}
case 'i': {
long inter_ccn_interval_l;
errno = 0;
inter_ccn_interval_l = strtol(optarg, (char **) NULL, 10);
if (errno || inter_ccn_interval_l < INT_MIN || inter_ccn_interval_l > INT_MAX) {
goto usage;
}
inter_ccn_interval = (int) inter_ccn_interval_l;
break;
}
#ifdef USE_ECHO
case 'o':
echopfx = optarg;
break;
#endif
case 'p':
crypto_sock_path = optarg;
break;
case 's':
suite = ccnl_str2suite(optarg);
if (!ccnl_isSuite(suite))
goto usage;
break;
case 't': {
long httpport_l;
errno = 0;
httpport_l = strtol(optarg, (char **) NULL, 10);
if (errno || httpport_l < INT_MIN || httpport_l > INT_MAX) {
goto usage;
}
httpport = (int) httpport_l;
break;
}
case 'u':
if (udpport1 == -1) {
long udpport1_l;
errno = 0;
udpport1_l = strtol(optarg, (char **) NULL, 10);
if (errno || udpport1_l < INT_MIN || udpport1_l > INT_MAX) {
goto usage;
}
udpport1 = (int) udpport1_l;
} else {
long udpport2_l;
errno = 0;
udpport2_l = strtol(optarg, (char **) NULL, 10);
if (errno || udpport2_l < INT_MIN || udpport2_l > INT_MAX) {
goto usage;
}
udpport2 = (int) udpport2_l;
}
break;
case '6':
if (udp6port1 == -1) {
long udp6port1_l;
errno = 0;
udp6port1_l = strtol(optarg, (char **) NULL, 10);
if (errno || udp6port1_l < INT_MIN || udp6port1_l > INT_MAX) {
goto usage;
}
udp6port1 = (int) udp6port1_l;
} else {
long udp6port2_l;
errno = 0;
udp6port2_l = strtol(optarg, (char **) NULL, 10);
if (errno || udp6port2_l < INT_MIN || udp6port2_l > INT_MAX) {
goto usage;
}
udp6port2 = (int) udp6port2_l;
}
break;
case 'v':
#ifdef USE_LOGGING
if (isdigit(optarg[0])) {
long debuglevel_l;
errno = 0;
debuglevel_l = strtol(optarg, (char **) NULL, 10);
if (errno || debuglevel_l < INT_MIN || debuglevel_l > INT_MAX) {
goto usage;
}
debug_level = (int) debuglevel_l;
} else {
debug_level = ccnl_debug_str2level(optarg);
}
#endif
break;
#ifdef USE_WPAN
case 'w':
wpandev = optarg;
break;
#endif
case 'x':
uxpath = optarg;
break;
case 'h':
default:
usage:
fprintf(stderr,
"usage: %s [options]\n"
" -c MAX_CONTENT_ENTRIES\n"
" -d databasedir\n"
" -e ethdev\n"
" -g MIN_INTER_PACKET_INTERVAL\n"
" -h\n"
" -i MIN_INTER_CCNMSG_INTERVAL\n"
#ifdef USE_ECHO
" -o echo_prefix\n"
#endif
" -p crypto_face_ux_socket\n"
" -s SUITE (ccnb, ccnx2015, ndn2013)\n"
" -t tcpport (for HTML status page)\n"
" -u udpport (can be specified twice)\n"
" -6 udp6port (can be specified twice)\n"
#ifdef USE_LOGGING
" -v DEBUG_LEVEL (fatal, error, warning, info, debug, verbose, trace)\n"
#endif
#ifdef USE_WPAN
" -w wpandev\n"
#endif
#ifdef USE_UNIXSOCKET
" -x unixpath\n"
#endif
, argv[0]);
exit(EXIT_FAILURE);
}
}
opt = ccnl_suite2defaultPort(suite);
if (udpport1 < 0) {
udpport1 = opt;
}
if (httpport < 0) {
httpport = opt;
}
ccnl_core_init();
DEBUGMSG(INFO, "This is ccn-lite-relay, starting at %s",
ctime(&theRelay->startup_time) + 4);
DEBUGMSG(INFO, " ccnl-core: %s\n", CCNL_VERSION);
DEBUGMSG(INFO, " compile time: %s %s\n", __DATE__, __TIME__);
DEBUGMSG(INFO, " compile options: %s\n", compile_string);
DEBUGMSG(INFO, " seed: %u\n", seed);
// DEBUGMSG(INFO, "using suite %s\n", ccnl_suite2str(suite));
ccnl_relay_config(theRelay, ethdev, wpandev, udpport1, udpport2,
udp6port1, udp6port2, httpport,
uxpath, suite, max_cache_entries, crypto_sock_path);
if (datadir) {
ccnl_populate_cache(theRelay, datadir);
}
#ifdef USE_ECHO
if (echopfx) {
struct ccnl_prefix_s *pfx;
char *dup = ccnl_strdup(echopfx);
pfx = ccnl_URItoPrefix(dup, suite, NULL);
if (pfx)
ccnl_echo_add(theRelay, pfx);
ccnl_free(dup);
}
#endif
ccnl_io_loop(theRelay);
while (eventqueue) {
ccnl_rem_timer(eventqueue);
}
ccnl_core_cleanup(theRelay);
#ifdef USE_HTTP_STATUS
theRelay->http = ccnl_http_cleanup(theRelay->http);
#endif
#ifdef USE_DEBUG_MALLOC
debug_memdump();
#endif
ccnl_free(theRelay);
return 0;
}
int
ccnl_static_fields1(){
return lasthour + inter_ccn_interval + inter_pkt_interval;
}
// eof
|
azadeh-afzar/CCN-IRIBU | src/ccnl-relay/ccn-lite-relay.h | <filename>src/ccnl-relay/ccn-lite-relay.h
/*
* @f ccn-lite-relay.c
* @b user space CCN relay
*
* Copyright (C) 2011-15, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2011-11-22 created
*/
#ifndef CCN_LITE_RELAY_H
#define CCN_LITE_RELAY_H
#include "ccnl-os-time.h"
extern struct ccnl_timer_s *eventqueue;
#endif // EOF
|
azadeh-afzar/CCN-IRIBU | src/ccnl-fwd/include/ccnl-echo.h | <gh_stars>10-100
/*
* @f ccnl-ext-echo.h
* @b CCN lite extension: echo/ping service - send back run-time generated data
*
* Copyright (C) 2015, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2015-01-12 created
*/
#ifndef CCN_LITE_CCNL_ECHO_H
#define CCN_LITE_CCNL_ECHO_H
#include "ccnl-core.h"
void
ccnl_echo_request(struct ccnl_relay_s *relay, struct ccnl_face_s *inface,
struct ccnl_prefix_s *pfx, struct ccnl_buf_s *buf);
int
ccnl_echo_add(struct ccnl_relay_s *relay, struct ccnl_prefix_s *pfx);
void
ccnl_echo_cleanup(struct ccnl_relay_s *relay);
#endif //CCN_LITE_CCNL_ECHO_H
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-http-status.h | <filename>src/ccnl-core/include/ccnl-http-status.h<gh_stars>10-100
/*
* @f ccn-http-status.h
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Created by <NAME> on 20.11.17.
*
*/
#ifndef CCN_LITE_CCNL_HTTP_STATUS_H
#define CCN_LITE_CCNL_HTTP_STATUS_H
#ifdef USE_HTTP_STATUS
#include "ccnl-core.h"
#include "ccnl-sockunion.h"
#include <time.h>
struct ccnl_http_s {
int server, client; // socket
unsigned char in[512], *out; // ring buffers
int inoffs, outoffs, inlen, outlen;
};
struct ccnl_http_s*
ccnl_http_new(struct ccnl_relay_s *ccnl, int serverport);
int ccnl_http_status(struct ccnl_relay_s *ccnl, struct ccnl_http_s *http);
struct ccnl_http_s*
ccnl_http_cleanup(struct ccnl_http_s *http);
int
ccnl_http_anteselect(struct ccnl_relay_s *ccnl, struct ccnl_http_s *http,
fd_set *readfs, fd_set *writefs, int *maxfd);
int
ccnl_http_postselect(struct ccnl_relay_s *ccnl, struct ccnl_http_s *http,
fd_set *readfs, fd_set *writefs);
int
ccnl_cmpfaceid(const void *a, const void *b);
int
ccnl_cmpfib(const void *a, const void *b);
int
ccnl_http_status(struct ccnl_relay_s *ccnl, struct ccnl_http_s *http);
#endif //USE_HTTP_STATUS
#endif //CCN_LITE_CCNL_HTTP_STATUS_H
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-prefix.h | <reponame>azadeh-afzar/CCN-IRIBU
/**
* @addtogroup CCNL-core
* @brief core library of CCN-Lite, contains important datastructures
* @{
* @file ccnl-prefix.h
* @brief CCN lite, core CCNx protocol logic
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*
* @copyright (C) 2011-18 University of Basel
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_PREFIX_H
#define CCNL_PREFIX_H
#include <stddef.h>
#ifndef CCNL_LINUXKERNEL
#include <stdint.h>
#else
#include <linux/types.h>
#endif
#ifndef CCNL_LINUXKERNEL
#include <unistd.h>
#endif
struct ccnl_content_s;
struct ccnl_prefix_s {
uint8_t **comp; /**< name components of the prefix without '\0' at the end */
size_t *complen; /**< length of the name components */
uint32_t compcnt; /**< number of name components */
char suite; /**< type of the packet format */
uint8_t *nameptr; /**< binary name (for fast comparison) */
ssize_t namelen; /**< valid length of name memory */
uint8_t *bytes; /**< memory for name component copies */
uint32_t *chunknum; /**< if defined, number of the chunk else -1 */
};
/**
* @brief Create a new CCNL_Prefix datastructure
*
* @param[in] suite Packet format for which the Prefix should be created
* @param[in] cnt Number of components which the Prefix should contain
*
* @return The created Prefix
*/
struct ccnl_prefix_s*
ccnl_prefix_new(char suite, uint32_t cnt);
/**
* @brief Frees CCNL_Prefix datastructure
*
* @param[in] prefix Prefix to be freed
*/
void
ccnl_prefix_free(struct ccnl_prefix_s *prefix);
/**
* @brief Duplicates CCNL_Prefix datastructure
*
* @param[in] prefix Prefix to be duplicated
*
* @return The duplicated Prefix
*/
struct ccnl_prefix_s*
ccnl_prefix_dup(struct ccnl_prefix_s *prefix);
/**
* @brief Add a component to a Prefix
*
* @param[in,out] prefix Prefix to which the component should be added
* @param[in] cmp Component which should be added
* @param[in] cmplen Length of the Component which should be added
*
* @return 0 on success else < 0
*/
int8_t
ccnl_prefix_appendCmp(struct ccnl_prefix_s *prefix, uint8_t *cmp, size_t cmplen);
/**
* @brief Set a Cunknum to a Prefix
*
* @param[in,out] prefix Prefix to which the component should be added
* @param[in] cunknum Chunknum which should be added
*
* @return 0 on success else < 0
*/
int
ccnl_prefix_addChunkNum(struct ccnl_prefix_s *prefix, uint32_t chunknum);
/**
* @brief Compares two Prefix datastructures
*
* @param[in] pfx Prefix 1 to be compared (shorter of Longest Prefix matching)
* @param[in] md ?
* @param[in] nam Prefix 2 to be compared (longer of Longest Prefix matching)
* @param[in] mode Mode for prefix comp (CMP_EXACT, CMP_MATCH, CMP_LONGEST)
*
* @return -1 if no match at all (all modes) or exact match failed
* @return 0 if full match (mode = CMP_EXACT) or no components match (mode = CMP_MATCH)
* @return n>0 for matched components (mode = CMP_MATCH, CMP_LONGEST)
*/
int32_t
ccnl_prefix_cmp(struct ccnl_prefix_s *pfx, unsigned char *md,
struct ccnl_prefix_s *nam, int mode);
/**
* @brief checks if a prefixname is a prefix of a content name
*
* @param[in] prefix Prefix to be compared (shorter of Longest Prefix matching)
* @param[in] minsuffix ?
* @param[in] maxsuffix ?
* @param[in] c Content to test the prefix against
*
* @return -1 if no match at all (all modes) or exact match failed
* @return -2 mismatch in expected number of components between prefix and content
* @return -3 computation of digest failed
* @return 0 if full match
* @return n>0 for matched components
*/
int8_t
ccnl_i_prefixof_c(struct ccnl_prefix_s *prefix,
uint64_t minsuffix, uint64_t maxsuffix, struct ccnl_content_s *c);
/**
* @brief checks if a prefixname is a prefix of a content name
*
* @param[in,out] comp component to be unescaped
*
* @return length of the escaped component
*/
size_t
unescape_component(char *comp);
//int
//ccnl_URItoComponents(char **compVector, unsigned int *compLens, char *uri);
/**
* @brief Take a URI and transform it into a CCNL_Prefix datastructure
*
* @param[in] URI The uri that should be transformed, components separated by '/'
* @param[in] suite Packet format of the prefix, that should be created
* @param[in] chunknum If prefix is part of a chunked data file, this contains the chunknumber
*
* @return The prefix datastruct that was created
*/
struct ccnl_prefix_s *
ccnl_URItoPrefix(char* uri, int suite, uint32_t *chunknum);
/**
* @brief Transforms a URI to a list of strings
*
* @param[out] compVector Resulting list of strings, without '\0' at the end
* @param[in] compLens length of the single components in compVector
* @param[in] uri The uri that should be transformed, components separated by '/'
*
* @return number of components that where added to compVector
*/
uint32_t
ccnl_URItoComponents(char **compVector, size_t *compLens, char *uri);
#ifndef CCNL_LINUXKERNEL
/**
* @brief Transforms a Prefix into a URI, separated by '/'
*
* @param[in] pr The prefix that should be transformed
* @param[in] ccntlv_skip Flag to enable skipping of CCNL_TLV fields
* @param[in] escape_components Flag to enable escaping components
* @param[in] call_slash Flag to enable call_slash
* @param[out] buf buffer to write the URI to
* @param[in] buf_len length of buffer @p buf
*
* @return the created URI @p buf
*/
char *
ccnl_prefix_to_str_detailed(struct ccnl_prefix_s *pr, int ccntlv_skip, int escape_components, int call_slash,
char *buf, size_t buflen);
/**
* @brief Transforms a Prefix into a URI, separated by '/'
*
* @note A buffer is allocated via `malloc` and passed to
* @ref ccnl_prefix_to_str_detailed
*
* @param[in] pr The prefix that should be transformed
* @param[in] ccntlv_skip Flag to enable skipping of CCNL_TLV fields
* @param[in] escape_components Flag to enable escaping components
* @param[in] call_slash Flag to enable call_slash
*
* @return the created URI
*/
char* ccnl_prefix_to_path_detailed(struct ccnl_prefix_s *pr, int ccntlv_skip, int escape_components, int call_slash);
# define ccnl_prefix_to_path(P) ccnl_prefix_to_path_detailed(P, 1, 0, 0)
# define ccnl_prefix_to_str(P, buf, buflen) ccnl_prefix_to_str_detailed(P, 1, 0, 0, buf, buflen)
#else
/**
* @brief Transforms a Prefix into a URI, separated bei '/'
*
* @param[in] pr The prefix that should be transformed
*
* @return the created URI
*/
char* ccnl_prefix_to_str(struct ccnl_prefix_s *pr, char* buf,size_t buflen);
char* ccnl_prefix_to_path(struct ccnl_prefix_s *pr);
#endif
/**
* @brief Transforms a Prefix into a URI, separated bei '/', that contains debug information
*
* @param[in] p The prefix that should be transformed
*
* @return the created URI containing debug information
*/
char*
ccnl_prefix_debug_info(struct ccnl_prefix_s *p);
#endif //EOF
/** @} */
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-producer.h | <filename>src/ccnl-core/include/ccnl-producer.h
/**
* @f ccnl-producer.h
* @b CCN lite, core CCNx protocol logic
*
* Copyright (C) 2011-18 University of Basel
* Copyright (C) 2015, 2016 INRIA
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2018-01-23 created (based on ccn-lite-riot.h)
*/
#ifndef CCNL_PRODUCER_H
#define CCNL_PRODUCER_H
#include "ccnl-core.h"
/**
* @brief Function pointer type for local producer function
*/
typedef int (*ccnl_producer_func)(struct ccnl_relay_s *relay,
struct ccnl_face_s *from,
struct ccnl_pkt_s *pkt);
/**
* @brief Set a local producer function
*
* Setting a local producer function allows to generate content on the fly or
* react otherwise on any kind of incoming interest.
*
* @param[in] func The function to be called first for any incoming interest
*/
void ccnl_set_local_producer(ccnl_producer_func func);
/**
* @brief Allows to generates content on the fly/or react to any kind of interest
*
* A developer has to provide its own local_producer function which is set via
* \ref ccnl_set_local_producer as a function pointer. If the function pointer
* is not, set the function simply returns '0'.
*
* @param[in] relay The active ccn-lite relay
* @param[in] from The face the packet was received over
* @param[in] pkt The actual received packet
*
* @return 0 if no function has been set
*/
#ifndef CCNL_ANDROID
int local_producer(struct ccnl_relay_s *relay, struct ccnl_face_s *from,
struct ccnl_pkt_s *pkt);
#else
#define local_producer(...) 0
#endif
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.