int SERV_PORT, mysql_port;
char mysql_host[FILELINE] = {}, mysql_user[FILELINE] = {}, mysql_pass[FILELINE] = {}, mysql_db[FILELINE] = {};
FILE *config;
char buf[FILELINE];
int buf_len = 0, non_infiniti = 0;
if ( ( config = fopen("server.conf", "r") ) == NULL)
{
printf("\"server.conf\" fopen error\n");
return 1;
}
do
{
non_infiniti++; // подстраховка, чтобы цикл не ушел в вечную петлю
fgets(buf, FILELINE, config);
// берем из конфига порт
if( strcmp(buf, "***port\n") == 0 )
{
fgets(buf, FILELINE, config);
SERV_PORT = atoi(buf);
continue;
}
if( strcmp(buf, "***mysql_host\n") == 0 )
{
fgets(buf, FILELINE, config);
buf_len = strlen(buf);
strncpy( &mysql_host[0], buf, buf_len - 1);
continue;
}
if( strcmp(buf, "***mysql_user\n") == 0 )
{
fgets(buf, FILELINE, config);
buf_len = strlen(buf);
strncpy( &mysql_user[0], buf, buf_len - 1);
continue;
}
if( strcmp(buf, "***mysql_pass\n") == 0 )
{
fgets(buf, FILELINE, config);
buf_len = strlen(buf);
strncpy( &mysql_pass[0], buf, buf_len - 1);
continue;
}
if( strcmp(buf, "***mysql_database\n") == 0 )
{
fgets(buf, FILELINE, config);
buf_len = strlen(buf);
strncpy( &mysql_db[0], buf, buf_len - 1);
continue;
}
if( strcmp(buf, "***mysql_port\n") == 0 )
{
fgets(buf, FILELINE, config);
mysql_port = atoi(buf);
continue;
}
if ( strcmp(buf, "***end\n") == 0)
break;
strcpy(buf, "");
} while (non_infiniti < 1000);
printf("%s\n", mysql_host);
printf("%s\n", mysql_user);
printf("%s\n", mysql_pass);
printf("%s\n", mysql_db);
printf("%d\n", mysql_port);
/** MySQL init **/
// Дескриптор соединения
MYSQL *rskdb;
// Дескриптор результирующей таблицы
MYSQL_RES *table;
// Дескриптор строки
MYSQL_ROW row;
rskdb = mysql_init(NULL);
if(rskdb == NULL)
{
// Если дескриптор не получен - выводим сообщение об ошибке
fprintf(stderr, "Error: can't create MySQL-descriptor\n");
exit(1);
}
// Подключаемся к серверу
// потом добавим подцепление из конфига
if(!mysql_real_connect(rskdb,
mysql_host,
mysql_user,
mysql_pass,
mysql_db,
mysql_port, //3306,
NULL,
0
))
{
// Если нет возможности установить соединение с сервером
// базы данных выводим сообщение об ошибке
fprintf(stderr,
"Error: can't connect to database %s\n",
mysql_error(rskdb));
return 1;
}
else
{
// Если соединение успешно установлено выводим фразу - "Success!"
fprintf(stdout, "Success!\n");
}
// Устанавливаем кодировку соединения, чтобы предотвратить
// искажения русского текста
if(mysql_query((MYSQL *)rskdb, "SET NAMES 'utf8'") != 0)
printf("Error: can't set character set\n");
/** creating listen socket **/
int fdserver, fdclient;
socklen_t client_len;
pid_t childpid;
struct sockaddr_in cliaddr, servaddr;
// сокет сервера
if ( (fdserver = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("cant make server socket\n");
return 1;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
//servaddr.sin_addr.s_addr = inet_pton(AF_INET, RSK_SERV_ADDR, &servaddr.sin_addr);
servaddr.sin_port = htons(SERV_PORT);
char myaddr[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &servaddr.sin_addr, myaddr, sizeof(myaddr));
printf("serv addres %s\nserv port %d\n", myaddr, SERV_PORT);
if ( (bind( fdserver, (struct sockaddr *) &servaddr, sizeof(servaddr))) < 0)
{
printf("binding error\n");
close(fdserver);
return 1;
}
if ( (listen(fdserver, 1024)) < 0)
{
printf("listening error\n");
close(fdserver);
return 1;
}
char strrecv[MAXLINE], *sendflag, *sendname, *sendlink, *command;
char SQL_QUESTION[] = "SELECT * FROM goal WHERE at_work = 0";
char SQL_UPDATE[] = "UPDATE rsk.goal g SET at_work = 1 WHERE link = \"";
//char *strsend
//strsend = (char *) malloc ( sizeof( char ) * MAXLINE );
command = (char *) malloc ( sizeof( char ) * MAXLINE);
sendflag = (char *) malloc ( sizeof( char ) * MAXLINE);
sendname = (char *) malloc ( sizeof( char ) * MAXLINE);
sendlink = (char *) malloc ( sizeof( char ) * MAXLINE);
for(;;)
{
client_len = sizeof(cliaddr);
if ((fdclient = accept(fdserver, (struct sockaddr *) &cliaddr, &client_len)) < 0)
{
printf("accepting error\n");
close(fdserver);
return 1;
}
if ( ( childpid = fork() ) == 0 ) // дочерний процесс
{
/*** child ***/
close(fdserver); // закрываем прослушивающий сокет
/** send encoding script **/
int exitflag = 0;
do
{
// Выполняем SQL-запрос
strcpy(command, SQL_QUESTION);
if( mysql_query((MYSQL *)rskdb, command) != 0)
{
printf("Error: can't execute SQL-query\n");
send(fdclient, "exit", MAXLINE, 0);
break;
}
// Получаем дескриптор результирующей таблицы
table = mysql_store_result((MYSQL *)rskdb);
if(table == NULL)
{
printf("Error: can't get the result description\n");
send(fdclient, "exit", MAXLINE, 0);
break;
}
// Если имеется хотя бы одна запись - выводим
// список каталогов
if(mysql_num_rows(table) > 0)
{
row = mysql_fetch_row(table);
sendlink = row[1];
sendname = row[3];
strcpy(command, SQL_UPDATE); // ... "
strcat(command, sendlink); // link
strcat(command, "\""); // "
mysql_query((MYSQL *)rskdb, command);
send(fdclient, "next goal", MAXLINE, 0);
printf("next goal\n");
printf("I send this name : %s\n", sendname);
send(fdclient, sendname, MAXLINE, 0);
printf("I send this link : %s\n", sendlink);
send(fdclient, sendlink, MAXLINE, 0);
}
else
{
send(fdclient, "exit", MAXLINE, 0);
exitflag = 1;
printf("Задачи кончились !!! bingo gl hf\n");
break;
}
// Освобождаем память, занятую результирующей таблицей
mysql_free_result(table);
// тут мы сможем узнать удачно завершилось кодирование или нет
recv(fdclient, strrecv, MAXLINE, 0);
printf("client answer %s\n", strrecv);
} while (exitflag != 1);
close(fdserver);
exit(0);
}
}
/** end **/
// Закрываем соединение с сервером базы данных
mysql_close(rskdb);
close(fdserver);
return 0;
}
***port
2011
***mysql_host
localhost
***mysql_user
rsk
***mysql_pass
123
***mysql_database
rsk
***mysql_port
3306
***end
Кодирующий скрипт encode_script.sh
#!/bin/bash
# $1 - source file
# $2 - target file
# $3 - tmp file
echo "sourse $1"
echo target $2
echo tmp $3
echo streams $4
cp $1 $3
mv $3 $2
exit
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <curl.h>
#include <types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <easy.h>
#define MAXLINE 300
#define FILELINE 200
#define OPT_SIZE 1000
#define SCRIPT "encode_script.sh"
#define MYTMP "tmp_files/tmp"
#define FILETYPE ".mp4"
struct FtpFile {
const char *filename;
FILE *stream;
};
static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
struct FtpFile *out=(struct FtpFile *)stream;
if(out && !out->stream) {
/* open file for writing */
out->stream=fopen(out->filename, "wb");
if(!out->stream)
return -1; /* failure, can't open file to write */
}
return fwrite(buffer, size, nmemb, out->stream);
}
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
/* in real-world cases, this would probably get this data differently
as this fread() stuff is exactly what the library already would do
by default internally */
size_t retcode = fread(ptr, size, nmemb, stream);
fprintf(stderr, "*** We read %d bytes from file\n", retcode);
return retcode;
}
int main()
{
char command[OPT_SIZE];
/** take config data **/
char RSK_SERV_ADDR[INET_ADDRSTRLEN] = {}, ftp_login[FILELINE] = {}, ftp_pass[FILELINE] = {}, ftp_link[FILELINE] = {};
char encode_streams[5] = {};
int SERV_PORT;
FILE *config;
if ( ( config = fopen("client.conf", "r") ) == NULL)
{
printf("\"client.conf\" fopen error\n");
return 1;
}
char buf[FILELINE];
int buf_len = 0, non_infiniti = 0;
do
{
non_infiniti++; // подстраховка, чтобы цикл не ушел в вечную петлю
strcpy(buf, "");
fgets(buf, FILELINE, config);
// берем из конфига порт
if( strcmp(buf, "***serv_port\n") == 0 )
{
fgets(buf, FILELINE, config);
SERV_PORT = atoi(buf);
continue;
}
if( strcmp(buf, "***serv_addres\n") == 0 )
{
fgets(buf, FILELINE, config);
buf_len = strlen(buf);
strncpy( &RSK_SERV_ADDR[0], buf, buf_len - 2);
strcat( &RSK_SERV_ADDR[0], "\0");
continue;
}
if( strcmp(buf, "***ftp_login\n") == 0 )
{
fgets(buf, FILELINE, config);
buf_len = strlen(buf);
strncpy( &ftp_login[0], buf, buf_len - 2);
strcat( &ftp_login[0], "\0");
continue;
}
if( strcmp(buf, "***ftp_pass\n") == 0 )
{
fgets(buf, FILELINE, config);
buf_len = strlen(buf);
strncpy( &ftp_pass[0], buf, buf_len - 2);
strcat( &ftp_pass[0], "\0");
continue;
}
if( strcmp(buf, "***ftp_link\n") == 0 )
{
fgets(buf, FILELINE, config);
buf_len = strlen(buf);
strncpy( &ftp_link[0], buf, buf_len - 2);
strcat( &ftp_link[0], "\0");
continue;
}
if( strcmp(buf, "***encode_streams\n") == 0 )
{
fgets(buf, FILELINE, config);
buf_len = strlen(buf);
strncpy( &encode_streams[0], buf, buf_len - 2);
strcat( &encode_streams[0], "\0");
continue;
}
if ( strcmp(buf, "***end\n") == 0)
break;
} while (non_infiniti < 1000);
/*printf("addr %s\nport %d \n", RSK_SERV_ADDR, SERV_PORT);
printf("login %s\n",ftp_login);
printf("pass %s\n",ftp_pass);
printf("link %s\n",ftp_link);
printf("stream %s\n",encode_streams);*/
/** connect to server **/
int fdclient;
struct sockaddr_in servaddr;
if ( ( fdclient = socket (AF_INET, SOCK_STREAM, 0) ) < 0 )
{
printf("socketing error\n");
return 1;
}
bzero( &servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, RSK_SERV_ADDR, &servaddr.sin_addr);
if ( ( connect(fdclient, (struct sockaddr *) &servaddr, sizeof(servaddr) ) ) < 0 )
{
printf("connection error\n");
close(fdclient);
return 1;
}
/** getting encoding script **/
// comming soon
// this summer
// movie "this programm are working"
strcpy( command, "chmod +rx ");
strcat( command, SCRIPT);
system( command);
/** data transfer **/
/* coding progress flag
* 1 - download file
* 2 - encode file
* 3 - upload file */
int progress = 0;
char recvflag[MAXLINE], recvname[MAXLINE], recvlink[MAXLINE];
char newname[MAXLINE];
// char strsend[MAXLINE];
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
for(;;)
{
// "exit" or "next step"
recv(fdclient, recvflag, MAXLINE, 0);
printf("recv flag %s\n", recvflag);
if( strcmp(recvflag, "exit") == 0)
{
send(fdclient, "exit", MAXLINE, 0);
break;
}
progress = 0;
recv(fdclient, recvname, MAXLINE, 0);
printf("name %s\n", recvname);
// newname - 4 simbols (.avi) + .mpeg4
buf_len = strlen(recvname);
strncpy(newname, recvname, buf_len - 4);
newname[buf_len - 4] = '\0';
//strcat(newname, ".mpeg4");
strcat(newname, FILETYPE);
//printf ("NEWNAME = %s[]\n", newname);
recv(fdclient, recvlink, MAXLINE, 0);
printf("I will download this link:\n%s\n", recvlink);
/** download **/
printf("\n\n DOWNLOADING \n\n");
curl = curl_easy_init();
struct FtpFile ftpfile={
recvname, /* name to store the file as if succesful */
NULL
};
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, recvlink);
/* Define our callback to get called when there's data to be written */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
/* Set a pointer to our struct to pass to the callback */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
/* Switch on full protocol/debug output */
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
if(CURLE_OK != res)
{
/* we failed */
fprintf(stderr, "curl told us %d\n", res);
send(fdclient, "download error error", MAXLINE, 0);
continue;
}
else
progress = 1;
}
if(ftpfile.stream)
fclose(ftpfile.stream); /* close the local file */
/** encoding **/
printf("\n\n ENCODING \n\n");
strcpy(command, "./");
strcat(command, SCRIPT);
strcat(command, " ");
strcat(command, recvname);
strcat(command, " ");
strcat(command, newname);
strcat(command, " ");
strcat(command, MYTMP);
strcat(command, " ");
strcat(command, encode_streams);
// printf("\n\n%s\n\n", command);
system(command);
/** upload **/
printf("\n\n UPLOADING\n\n");
FILE *hd_src;
struct stat file_info;
if(stat(newname, &file_info)) {
printf("Couldnt open '%s': %s\n", newname, strerror(errno));
send(fdclient, "upload error error", MAXLINE, 0);
continue;
}
hd_src = fopen(newname, "rb");
/* get a curl handle */
curl = curl_easy_init();
if(curl) {
/* we want to use our own read function */