code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/runner' | 10pockets | trunk/script/runner | Ruby | mit | 96 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/about' | 10pockets | trunk/script/.svn/text-base/about.svn-base | Ruby | mit | 95 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/generate' | 10pockets | trunk/script/.svn/text-base/generate.svn-base | Ruby | mit | 98 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/breakpointer' | 10pockets | trunk/script/.svn/text-base/breakpointer.svn-base | Ruby | mit | 102 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/server' | 10pockets | trunk/script/.svn/text-base/server.svn-base | Ruby | mit | 96 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/plugin' | 10pockets | trunk/script/.svn/text-base/plugin.svn-base | Ruby | mit | 96 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/destroy' | 10pockets | trunk/script/.svn/text-base/destroy.svn-base | Ruby | mit | 97 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/runner' | 10pockets | trunk/script/.svn/text-base/runner.svn-base | Ruby | mit | 96 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/console' | 10pockets | trunk/script/.svn/text-base/console.svn-base | Ruby | mit | 97 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/console' | 10pockets | trunk/script/console | Ruby | mit | 97 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/server' | 10pockets | trunk/script/server | Ruby | mit | 96 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/about' | 10pockets | trunk/script/about | Ruby | mit | 95 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/destroy' | 10pockets | trunk/script/destroy | Ruby | mit | 97 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/generate' | 10pockets | trunk/script/generate | Ruby | mit | 98 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/performance/benchmarker'
| 10pockets | trunk/script/performance/benchmarker | Ruby | mit | 117 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/performance/profiler'
| 10pockets | trunk/script/performance/.svn/text-base/profiler.svn-base | Ruby | mit | 114 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/performance/benchmarker'
| 10pockets | trunk/script/performance/.svn/text-base/benchmarker.svn-base | Ruby | mit | 117 |
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/performance/profiler'
| 10pockets | trunk/script/performance/profiler | Ruby | mit | 114 |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| 10pockets | trunk/public/javascripts/application.js | JavaScript | mit | 148 |
/*
Automatic, anti-aliased rounded corners.
By Steven Wittens
Based on http://pro.html.it/esempio/nifty/
Thanks to Jacob from Oddlabs.com for fixing two nasty bugs.
*/
function NiftyCheck() {
if(!document.getElementById || !document.createElement) {
return false;
}
var b = navigator.userAgent.toLowerCase();
if (b.indexOf("msie 5") > 0 && b.indexOf("opera") == -1) {
return false;
}
return true;
}
function Rounded(selector, bk, color, sizex, sizey) {
var i;
var v = getElementsBySelector(selector);
var l = v.length;
for (i = 0; i < l; i++) {
AddTop(v[i], bk, color, sizex, sizey);
AddBottom(v[i], bk, color, sizex, sizey);
}
}
Math.sqr = function (x) {
return x*x;
};
function Blend(a, b, alpha) {
var ca = Array(
parseInt('0x' + a.substring(1, 3)),
parseInt('0x' + a.substring(3, 5)),
parseInt('0x' + a.substring(5, 7))
);
var cb = Array(
parseInt('0x' + b.substring(1, 3)),
parseInt('0x' + b.substring(3, 5)),
parseInt('0x' + b.substring(5, 7))
);
r = '0' + Math.round(ca[0] + (cb[0] - ca[0])*alpha).toString(16);
g = '0' + Math.round(ca[1] + (cb[1] - ca[1])*alpha).toString(16);
b = '0' + Math.round(ca[2] + (cb[2] - ca[2])*alpha).toString(16);
return '#'
+ r.substring(r.length - 2)
+ g.substring(g.length - 2)
+ b.substring(b.length - 2);
}
function AddTop(el, bk, color, sizex, sizey) {
var i, j;
var d = document.createElement("div");
d.style.backgroundColor = bk;
d.className = "rounded";
var lastarc = 0;
for (i = 1; i <= sizey; i++) {
var coverage, arc2, arc3;
// Find intersection of arc with bottom of pixel row
arc = Math.sqrt(1.0 - Math.sqr(1.0 - i / sizey)) * sizex;
// Calculate how many pixels are bg, fg and blended.
var n_bg = sizex - Math.ceil(arc);
var n_fg = Math.floor(lastarc);
var n_aa = sizex - n_bg - n_fg;
// Create pixel row wrapper
var x = document.createElement("div");
var y = d;
x.style.margin = "0px " + n_bg +"px";
// Make a wrapper per anti-aliased pixel (at least one)
for (j = 1; j <= n_aa; j++) {
// Calculate coverage per pixel
// (approximates circle by a line within the pixel)
if (j == 1) {
if (j == n_aa) {
// Single pixel
coverage = ((arc + lastarc) * .5) - n_fg;
}
else {
// First in a run
arc2 = Math.sqrt(1.0 - Math.sqr(1.0 - (n_bg + 1) / sizex)) * sizey;
coverage = (arc2 - (sizey - i)) * (arc - n_fg - n_aa + 1) * .5;
}
}
else if (j == n_aa) {
// Last in a run
arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
coverage = 1.0 - (1.0 - (arc2 - (sizey - i))) * (1.0 - (lastarc - n_fg)) * .5;
}
else {
// Middle of a run
arc3 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j) / sizex)) * sizey;
arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
coverage = ((arc2 + arc3) * .5) - (sizey - i);
}
x.style.backgroundColor = Blend(bk, color, coverage);
y.appendChild(x);
y = x;
var x = document.createElement("div");
x.style.margin = "0px 1px";
}
x.style.backgroundColor = color;
y.appendChild(x);
lastarc = arc;
}
el.insertBefore(d, el.firstChild);
}
function AddBottom(el, bk, color, sizex, sizey) {
var i, j;
var d = document.createElement("div");
d.className = "rounded";
d.style.backgroundColor = bk;
var lastarc = 0;
for (i = 1; i <= sizey; i++) {
var coverage, arc2, arc3;
// Find intersection of arc with bottom of pixel row
arc = Math.sqrt(1.0 - Math.sqr(1.0 - i / sizey)) * sizex;
// Calculate how many pixels are bg, fg and blended.
var n_bg = sizex - Math.ceil(arc);
var n_fg = Math.floor(lastarc);
var n_aa = sizex - n_bg - n_fg;
// Create pixel row wrapper
var x = document.createElement("div");
var y = d;
x.style.margin = "0px " + n_bg + "px";
// Make a wrapper per anti-aliased pixel (at least one)
for (j = 1; j <= n_aa; j++) {
// Calculate coverage per pixel
// (approximates circle by a line within the pixel)
if (j == 1) {
if (j == n_aa) {
// Single pixel
coverage = ((arc + lastarc) * .5) - n_fg;
}
else {
// First in a run
arc2 = Math.sqrt(1.0 - Math.sqr(1.0 - (n_bg + 1) / sizex)) * sizey;
coverage = (arc2 - (sizey - i)) * (arc - n_fg - n_aa + 1) * .5;
}
}
else if (j == n_aa) {
// Last in a run
arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
coverage = 1.0 - (1.0 - (arc2 - (sizey - i))) * (1.0 - (lastarc - n_fg)) * .5;
}
else {
// Middle of a run
arc3 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j) / sizex)) * sizey;
arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
coverage = ((arc2 + arc3) * .5) - (sizey - i);
}
x.style.backgroundColor = Blend(bk, color, coverage);
y.insertBefore(x, y.firstChild);
y = x;
var x = document.createElement("div");
x.style.margin = "0px 1px";
}
x.style.backgroundColor = color;
y.insertBefore(x, y.firstChild);
lastarc = arc;
}
el.appendChild(d);
}
function getElementsBySelector(selector) {
var i;
var s = [];
var selid = "";
var selclass = "";
var tag = selector;
var objlist = [];
if (selector.indexOf(" ") > 0) { //descendant selector like "tag#id tag"
s = selector.split(" ");
var fs = s[0].split("#");
if (fs.length == 1) {
return objlist;
}
return document.getElementById(fs[1]).getElementsByTagName(s[1]);
}
if (selector.indexOf("#") > 0) { //id selector like "tag#id"
s = selector.split("#");
tag = s[0];
selid = s[1];
}
if (selid != "") {
objlist.push(document.getElementById(selid));
return objlist;
}
if (selector.indexOf(".") > 0) { //class selector like "tag.class"
s = selector.split(".");
tag = s[0];
selclass = s[1];
}
var v = document.getElementsByTagName(tag); // tag selector like "tag"
if (selclass == "") {
return v;
}
for (i = 0; i < v.length; i++) {
if (v[i].className == selclass) {
objlist.push(v[i]);
}
}
return objlist;
}
| 10pockets | trunk/public/javascripts/nifty.js | JavaScript | mit | 6,588 |
/* styles for the star rater */
.star-rating{
list-style:none;
margin-top:5px;
margin-right:10px;
padding:0px;
width: 125px;
height: 25px;
position: relative;
float:left;
background: url(alt_star.gif) top left repeat-x;
}
.star-rating li{
padding:0px;
margin:0px;
/*\*/
float: left;
/* */
}
.star-rating li a{
display:block;
width:25px;
height: 25px;
text-decoration: none;
text-indent: -9000px;
z-index: 20;
position: absolute;
padding: 0px;
}
.star-rating li a:hover{
background: url(alt_star.gif) left bottom;
margin-top:-1px;
z-index: 2;
left: 0px;
}
.star-rating a.one-star{
left: 0px;
}
.star-rating a.one-star:hover{
width:25px;
}
.star-rating a.two-stars{
left:25px;
}
.star-rating a.two-stars:hover{
width: 50px;
}
.star-rating a.three-stars{
left: 50px;
}
.star-rating a.three-stars:hover{
width: 75px;
}
.star-rating a.four-stars{
left: 75px;
}
.star-rating a.four-stars:hover{
width: 100px;
}
.star-rating a.five-stars{
left: 100px;
}
.star-rating a.five-stars:hover{
width: 125px;
}
.star-rating li.current-rating{
background: url(alt_star.gif) left center;
position: absolute;
height: 25px;
display: block;
text-indent: -9000px;
z-index: 1;
}
/* styles for the star rater */
.star-rating-noh{
list-style:none;
margin-right:10px;
margin-top:5px;
padding:0px;
width: 125px;
height: 25px;
position: relative;
float:left;
background: url(alt_star.gif) top left repeat-x;
}
.star-rating-noh lidd{
padding:0px;
margin:0px;
/*\*/
float: left;
/* */
}
.star-rating-noh li{
display:block;
width:25px;
height: 25px;
text-decoration: none;
text-indent: -9000px;
z-index: 20;
position: absolute;
padding: 0px;
}
.star-rating-noh li.current-rating{
background: url(alt_star.gif) left bottom;
position: absolute;
height: 25px;
display: block;
text-indent: -9000px;
z-index: 1;
}
.star-rating-noh li.one-star{
left: 0px;
}
.star-rating-noh li.two-stars{
left:25px;
}
.star-rating-noh li.three-stars{
left: 50px;
}
.star-rating-noh li.four-stars{
left: 75px;
}
.star-rating-noh li.five-stars{
left: 100px;
}
| 10pockets | trunk/public/images/star_rating/star.css | CSS | mit | 2,473 |
body { background-color: #fff; color: #333; }
body, p, ol, ul, td {
font-family: verdana, arial, helvetica, sans-serif;
font-size: 13px;
line-height: 18px;
}
pre {
background-color: #eee;
padding: 10px;
font-size: 11px;
}
a { color: #000; }
a:visited { color: #666; }
a:hover { color: #fff; background-color:#000; }
.fieldWithErrors {
padding: 2px;
background-color: red;
display: table;
}
#errorExplanation {
width: 400px;
border: 2px solid red;
padding: 7px;
padding-bottom: 12px;
margin-bottom: 20px;
background-color: #f0f0f0;
}
#errorExplanation h2 {
text-align: left;
font-weight: bold;
padding: 5px 5px 5px 15px;
font-size: 12px;
margin: -7px;
background-color: #c00;
color: #fff;
}
#errorExplanation p {
color: #333;
margin-bottom: 0;
padding: 5px;
}
#errorExplanation ul li {
font-size: 12px;
list-style: square;
}
div.uploadStatus {
margin: 5px;
}
div.progressBar {
margin: 5px;
}
div.progressBar div.border {
background-color: #fff;
border: 1px solid grey;
width: 100%;
}
div.progressBar div.background {
background-color: #333;
height: 18px;
width: 0%;
}
| 10pockets | trunk/public/stylesheets/scaffold.css | CSS | mit | 1,152 |
* { margin: 0; padding: 0; outline: 0; }
body {background: #caced1;font: 70%/1.5em Verdana, Tahoma, arial, sans-serif;color: #777;text-align: center;margin: 15px 0;}
a, a:visited {text-decoration: none;background: inherit;color: #FB9233;}
a:hover {text-decoration: underline;background: inherit;color: #93C600;}
h1, h2, h3 { font-family: 'Trebuchet MS', Tahoma, Sans-serif; }
h1 {font-size: 180%;font-weight: normal;color: #555;}
h2 {font-size: 160%;color: #88ac0b;font-weight: normal;}
h3 {font-size: 135%;color: #666666;}
h1, h2, h3, p {margin: 10px 15px;padding: 0;}
code {margin: 5px 0;padding: 15px;text-align: left;display: block;overflow: auto;font: 500 1em/1.5em 'Lucida Console', 'courier new', monospace ;border: 1px solid #E5F0FB;background: #F4F8FD;}
acronym {cursor: help;border-bottom: 1px dotted #777;}
blockquote {margin: 10px 15px;padding: 0 0 0 25px;font: bold 1.3em/1.5em "Trebuchet MS", Tahoma, arial, Sans-serif;color: #2361BA;border: 1px solid #E5F0FB;background: #F4F8FD url("/images/quote.jpg") no-repeat 8px 6px;}
table {border-collapse: collapse;margin: 10px 15px;}
th strong {color: #fff;}
th {background: #306bc1 url("/images/button-bg.jpg") repeat-x 0 0;font-size:9px;height: 35px;padding-left: 12px;padding-right: 12px;color: #fff;text-align: left;border: 1px solid #306bc1;border-bottom-width: 2px;}
tr {height: 32px;background: #fff;}
td {padding-left: 12px;padding-right: 12px;border: 1px solid #E5F0FB;}
form {margin:10px 15px;padding: 10px 0;border: 1px solid #E5F0FB;background: #F4F8FD;}
fieldset {margin: 0; padding: 0;border: none;}
legend {display: none;}
label {display:block;font-weight:bold;margin: 7px 0;}
input {padding:3px;border: 1px solid #25c03B;font: normal 1em Verdana, sans-serif;color:#777;}
textarea {width:400px;padding:3px;font: normal 1em Verdana, sans-serif;border: 1px solid #E5F0FB;height:100px;display:block;color:#777;}
input.button,input.submit,input.submit-s,input.log2 {font: bold 12px Arial, Sans-serif;height: 28px;margin: 0;padding: 2px 3px;color: #fff;background: #306bc1 url("/images/button-bg.jpg") repeat-x 0 0;border: 1px solid #306bc1;}
.searchform {background-color: transparent;border: none;margin: 0;padding: 5px 0 5px 0;width: 180px;}
.searchform p { margin: 0; padding: 0; }
.searchform input.textbox {width: 110px;color: #777;height: 20px;padding: 2px;border: 1px solid #D2E8F7;vertical-align: top;
}.searchform input.button {width: 55px;height: 26px;padding: 2px 5px;vertical-align: top;}
#wrap {width: 790px;background: #CCC url("/images/content.jpg") repeat-y center top;margin: 0 auto;text-align: left;}
#content-wrap {clear: both;width: 760px;margin: 5px auto;padding: 0;}
#header {position: relative;height: 131px;background: #caced1 url("/images/header.jpg") no-repeat center top;padding: 0;color: #fff;}
#header h1#logo-text a {position: absolute;margin: 0; padding: 0;font: bolder 55px 'Trebuchet MS', Arial, Sans-serif;letter-spacing: -3px;color: #fff;text-transform: none;text-decoration: none;background: transparent;top: 18px; left: 35px;}
#header p#slogan {position: absolute;margin: 0; padding: 0;font: bold 13px 'Trebuchet MS', Arial, Sans-serif;text-transform: none;color: #FFF;top: 80px; left: 50px;}
#header #header-links {position: absolute;color: #C6DDEE;font: bold 14px"Trebuchet MS", Arial, Tahoma, Sans-serif;top: 20px; right: 20px;}
#header #header-links a {color: #fff;text-decoration: none;}
#header #header-links a:hover {color: #D4FF55;}
#menu {clear: both;margin: 0 auto; padding: 0;background: #81C524 url("/images/menu.jpg") no-repeat;font: bold 16px/40px "trebuchet MS", Arial, Tahoma, Sans-serif;height: 40px;width: 790px;}
#menu ul {float: left;list-style: none;margin:0; padding: 0 0 0 20px;}
#menu ul li {display: inline;}
#menu ul li a {display: block;float: left;padding: 0 12px;color: #fff;text-decoration: none;background: url("/images/sep.jpg") no-repeat 100% 100%;}
#menu ul li a:hover {color: #3b5e0b;}
#menu ul li#current a {color: #3b5e0b;}
#main {float: left;width: 545px;margin: 0; padding: 20px 0 0 0;display: inline;}
#main h2 {font: normal 180% 'Trebuchet MS', Tahoma, Arial, Sans-serif;padding: 0;margin-bottom: 0;color: #2666c3;}
#main h2 a {color: #2666c3;text-decoration: none;}
#main blockquote, #main table, #main form {margin-left: 20px;margin-right: 25px;}
#sidebar {float: right;width: 195px;padding: 0; margin: 0px 0 0 0;color: #777;}
#sidebar h2 {margin: 15px 5px 10px 5px;font: bold 1.4em 'Trebuchet MS', Tahoma, Sans-serif;color: #555;}
#sidebar p {margin-left: 0px;}
#footer {color: #C6DDEE;background: #caced1 url("/images/footer.jpg") no-repeat center top;clear: both;width: 790px;height: 57px;text-align: center;font-size: 90%;}
#footer p {padding: 10px 0;margin: 0;}
#footer a {color: #fff;text-decoration: none;}
.float-left { float: left; }
.float-right { float: right; }
.align-left { text-align: left; }
.align-right { text-align: right; }
.clear { clear: both; }
/*Pligg Code*/
hr {background:#f2f2f2;height:1px;color:#f2f2f2;border:none;clear:both;margin:1em 0;}
.news-summary {position:relative;clear:left;width:100%;padding:1px 0 10px;}
.top {margin-left:60px;padding:0 0 0 5px;}
.top h4 {padding-left:4px;font-size:160%;font-weight:400;margin:0;}
.top h4 a:link,.top h4 a:visited {color:#FB9233;font-weight:700;}
.toptitle {font-size:16px;font-weight:400;margin:0;}
.toptitle a:link,.toptitle a:visited {color:#FB9233;font-weight:700;}
.toptitle a:hover {color:#93C600;}
.news-submitted {font-size:85%;margin-bottom:3px;color:#999;}
.news-submitted a {color:#999;text-decoration:underline;}
.news-submitted img {float:left;margin-right:4px;margin-top:3px;vertical-align:bottom;z-index: 1;position:relative;}
.news-body-text {font-size:96%;margin:10px 0 0;}
.news-details {font-size:85%;margin:0;}
.news-details a:hover,.news-details a:active {color:#93C600;text-decoration:underline;}
.news-details b {color:#c00;}
* html .news-details {padding-right:136px;}
.news-details .comments_no {padding-left:37px;border-left:none;}
ul.news-details li li {border-left:none;float:none;height:21px;}
.news-upcoming {background:url("/images/vote-l.png") no-repeat 0 0;position:absolute;top:3px;left:0;width:55px;text-align:center;font-size:85%;list-style:none;margin:0;padding:0;}
.news-upcoming2 {background:url("/images/vote-l.png") no-repeat 0 0;position:absolute;top:3px;left:0;width:55px;text-align:center;font-size:85%;list-style:none;margin:0;padding:0;}
.vote-publish a {font-size:26px;color:#FFFFFF;letter-spacing:-1px;text-decoration:none;line-height:48px;padding:15px 0 6px;}
.vote-publish a small {font-size:12px;letter-spacing:0;text-decoration:none;}
.vote-publish a:hover,.vote-publish a:active {text-decoration:none;color:#93C600;}
.vote a:link,.vote a:visited,.vote span {display:block;color:#FB9233;font-size:12px;text-decoration:none;padding:3px 0 5px;}
.vote span {color:#93C600;font-size:11px;}
#comment-wrap {border-bottom:solid 1px #e1e1e1;}
#comment-head {background:#e1e1e1;width:100%;}
.comment-body {background:#fafafa;padding:0 4px;}
.comment-info {background:#fafafa;font-size:80%;text-align:right;padding-right:4px;}
.avatar {float:left;width:15px;height:15px;margin:1px 0 0;}
#comment-subhead {float:right;margin-top:-21px;font-size:11px;}
.ratemey {background:#090;padding:1px 5px;}
.ratemen {background:#c00;color:#fff;padding:1px 6px;}
.rateme {color:#fff;font-size:14px;}
#stats {width:48%;float:right;}
#personal_info {width:48%;float:left;}
.live2 {background-repeat:no-repeat;background-position:bottom right;margin:10px;}
.live2 strong {font-size:95%;}
.live2-item {width:100%;clear:both;border-bottom:1px solid #ccc;min-height:25px;text-align:center;overflow:hidden;padding:5px 2px 0;}
.live2-ts,.live2-type,.live2-votes,.live2-story,.live2-who,.live2-status {float:left;display:block;}
.live2-type img {border:none;vertical-align:middle;margin:0;}
.live2-story {width:37%;text-align:left;}
.live2-who {width:18%;text-align:left;}
.live2-status {width:15%;text-align:left;}
.live2-problem {color:red;}
.pagination {background:#f2f2f2;color:#666;border:1px solid #ddd;margin:0 0 1.5em;padding:4px 2px 4px 7px;}
.pagination p {position:relative;text-align:left;}
.pagination p a:link,.pagination p a:visited,.pagination p a:hover,.pagination p a:active {text-decoration:none;background:#fff;border:1px solid #ccc;margin-right:1px;padding:2px 5px;}
.pagination p a:hover {background:#1773BC;color:#fff;}
.pagination p span {text-decoration:none;background:#1773BC;border:1px solid #ccc;color:#ccc;margin-right:1px;padding:2px 5px;}
.pagination h4 {margin-top:-1.45em;border:none;padding:0;}
#cab {height:30px;margin-left:20px;font-size:9px;}
#navbar {color:#666;font-size:9px;padding-bottom:5px;}
#story-navbar {color:#666;font-size:11px;margin:2px 20px 0;padding:0px 0 7px 10px;}
#cab ul {list-style:none;padding:0 10px 0 30px;}
#cab li {float:left;text-align:center;display:block;}
#cab a.navbut3 {float:left;background:url("/images/tabrB2.png") no-repeat right top;text-decoration:none;display:block;height:33px;color:#1773BC;font-weight:700;margin:0 1px;padding:0 6px 0 0;}
#cab a.navbut3:hover {background:url("/images/tabrightB.png") no-repeat right top;color:#000000;}
#cab a.navbut3 span {float:left;background:url("/images/tablB2.png") no-repeat left top;text-align:center;display:block;height:33px;padding:9px 0 5px 6px;}
#cab a.navbut3:hover span {background:url("/images/tableftB.png") no-repeat left top;}
#cab a.navbut4 {float:left;background:url("/images/tabrightB.png") no-repeat right top;text-decoration:none;display:block;height:33px;color:#000;font-weight:700;margin:0 1px;padding:0 6px 0 0;}
#cab a.navbut4 span {float:left;background:url("/images/tableftB.png") no-repeat left top;text-align:center;display:block;height:33px;padding:9px 0 5px 6px;}
.cab {padding:0 10px 30px 5px;}
.cab span a {background:url("/images/story_tab2.png") no-repeat 0 0;display:block;float:left;width:100px;height:33px;text-align:center;text-decoration:none;color:#1773BC;font-weight:700;padding:8px 0 0 2px;}
.news-details .tool,.news-details .tool-right {display:block;float:left;padding:0 4px;}
.live2-ts,.live2-type,.live2-votes {width:10%;text-align:left;}
#headbar form,.pagination * {margin:0;}
#headbar ul a,#navbar a {color:#ce4a02;text-decoration:none;}
#headbar ul a:hover,#navbar a:hover {text-decoration:underline;}
#sorts {vertical-align:middle;margin-bottom:15px;}
#sorts a{ color:#578cca; font-size:12px}
#sorts a:hover { color:#333333}
#sorts span {font-size:16px; color:#E45B00; font-weight:bold}
#sorts img {margin-bottom:0px;}
#sorts a:hover,#cab a,#cab span a:hover,.top h4 a:hover,.vote a:hover {color:#000;}
.cab span.selected,.tlb2 span.selected {cursor:text;font-weight:700;color:#666;text-align:center;}
.cab span.selected a,.cab span a:hover {background:url("/images/story_tab.png") no-repeat 0 0;display:block;float:left;width:100px;height:33px;text-decoration:none;color:#000;font-weight:700;padding:8px 0 0 2px;}
.error {color:#c00;font-weight:700;margin-top:10px;border:1px solid red;background:#FFC5BE;padding:5px;}
.success {color:#390;font-weight:700;}
*,fieldset dl {margin:0;padding:0;}
#contentbox #breadcrumb a:link,#contentbox #breadcrumb a:hover,#contentbox #breadcrumb a,#content #breadcrumb a:active,#content #breadcrumb a:visited,.news-submitted a:hover {text-decoration:none;}
table,#wrapper,#bookmarklet {width:95%;}
.featurebox {color:#1773BC;margin:0 0 15px;padding:15px 0 0 10px;}
.featurebox p {border:none;color:#1773BC;margin:0 0 1em;}
.featurebox a:hover {color:#333;text-decoration:underline;}
.featurebox li a {margin-left:-10px;padding-left:20px;line-height:2em;}
.featurebox li.rmore {list-style:none;margin-left:90px;}
.featurebox li.rmore a {text-decoration:none;font-size:12px;line-height:2.2em;}
.featurebox ul {margin-left:10px;margin-bottom:10px;}
.featurebox ul a {margin-bottom:5px;}
.tlb {margin:-15px -10px 0;padding:3px 10px 5px;}
.tlb a {font-weight:700;color:#1773BC;text-decoration:none;font-size:14px;}
.tlb strong {font-weight:700;color:#1773BC;}
.tlb a:hover {color:#333;text-decoration:none;}
.tlb span {float:right;margin-top:-3px;margin-right:0;}
.tlb2 {margin:5px 0 0;padding:0 0 20px;}
.tlb2 span a {background:url("/images/exp_on.png") no-repeat 0 0;margin-right:8px;cursor:pointer;float:left;display:block;color:#66c;width:58px;height:21px;text-align:center;padding-top:2px;}
.tlb2 span.selected a {background:url("/images/exp_down.png") no-repeat 0 0;width:58px;height:21px;cursor:text;float:left;display:block;margin-right:8px;font-weight:700;color:#666;text-align:center;padding-top:2px;}
.sstories {padding-top:3px;padding-right:13px;float:left;}
.count_total {margin-left:8px;color:#1773BC;font-weight:700;font-size:110%;}
#nav-secondary,#nav-secondary ul {position:static;margin:0;}
#nav-secondary,#nav-secondary li {list-style:none;display:block;margin:0;padding:0;}
#nav-secondary {padding-top:0;margin-top:10px;}
#nav-secondary a {line-height:1.5;font:96% arial;display:block;color:#1773BC;border-bottom:1px solid #A9D4EF;}
#nav-secondary a:hover {color:#333;}
a.switchurl {border-bottom:1px solid #A9D4EF;display:block;margin-right:8px;padding:0 0 4px 5px;}
.featurebox a,.news-details a:link,.news-details a:visited {color:#1773BC;text-decoration:none;}
.linksum { clear: both; padding-top: 10px;}
.css1 { font-size: 1.0em; }
.css2 { font-size: 1.2em; }
.css3 { font-size: 1.4em; }
.css4 { font-size: 1.6em; }
| 10pockets | trunk/public/stylesheets/style.css | CSS | mit | 13,570 |
.featurebox li.rmore {margin-left:130px;}
h1, h2, h3, h4, h5, h6 {position:relative;}
#navbar {margin:-1px 20px 0 20px;}
#cab ul {padding:0px 0px 0px 15px;margin-left:-8px;} | 10pockets | trunk/public/stylesheets/ie6.css | CSS | mit | 182 |
#!/opt/local/bin/ruby
#
# You may specify the path to the FastCGI crash log (a log of unhandled
# exceptions which forced the FastCGI instance to exit, great for debugging)
# and the number of requests to process before running garbage collection.
#
# By default, the FastCGI crash log is RAILS_ROOT/log/fastcgi.crash.log
# and the GC period is nil (turned off). A reasonable number of requests
# could range from 10-100 depending on the memory footprint of your app.
#
# Example:
# # Default log path, normal GC behavior.
# RailsFCGIHandler.process!
#
# # Default log path, 50 requests between GC.
# RailsFCGIHandler.process! nil, 50
#
# # Custom log path, normal GC behavior.
# RailsFCGIHandler.process! '/var/log/myapp_fcgi_crash.log'
#
require File.dirname(__FILE__) + "/../config/environment"
require 'fcgi_handler'
RailsFCGIHandler.process!
| 10pockets | trunk/public/dispatch.fcgi | Ruby | mit | 861 |
#!/opt/local/bin/ruby
require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
require "dispatcher"
ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
Dispatcher.dispatch | 10pockets | trunk/public/dispatch.cgi | Ruby | mit | 479 |
#!/opt/local/bin/ruby
require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
require "dispatcher"
ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
Dispatcher.dispatch | 10pockets | trunk/public/dispatch.rb | Ruby | mit | 479 |
#!/opt/local/bin/ruby
require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
require "dispatcher"
ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
Dispatcher.dispatch | 10pockets | trunk/public/.svn/text-base/dispatch.rb.svn-base | Ruby | mit | 479 |
#!/opt/local/bin/ruby
#
# You may specify the path to the FastCGI crash log (a log of unhandled
# exceptions which forced the FastCGI instance to exit, great for debugging)
# and the number of requests to process before running garbage collection.
#
# By default, the FastCGI crash log is RAILS_ROOT/log/fastcgi.crash.log
# and the GC period is nil (turned off). A reasonable number of requests
# could range from 10-100 depending on the memory footprint of your app.
#
# Example:
# # Default log path, normal GC behavior.
# RailsFCGIHandler.process!
#
# # Default log path, 50 requests between GC.
# RailsFCGIHandler.process! nil, 50
#
# # Custom log path, normal GC behavior.
# RailsFCGIHandler.process! '/var/log/myapp_fcgi_crash.log'
#
require File.dirname(__FILE__) + "/../config/environment"
require 'fcgi_handler'
RailsFCGIHandler.process!
| 10pockets | trunk/public/.svn/text-base/dispatch.fcgi.svn-base | Ruby | mit | 861 |
#!/opt/local/bin/ruby
require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
require "dispatcher"
ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
Dispatcher.dispatch | 10pockets | trunk/public/.svn/text-base/dispatch.cgi.svn-base | Ruby | mit | 479 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>The page you were looking for doesn't exist (404)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/404.html -->
<div class="dialog">
<h1>The page you were looking for doesn't exist.</h1>
<p>You may have mistyped the address or the page may have moved.</p>
</div>
</body>
</html> | 10pockets | trunk/public/404.html | HTML | mit | 947 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>We're sorry, but something went wrong</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/500.html -->
<div class="dialog">
<h1>We're sorry, but something went wrong.</h1>
<p>We've been notified about this issue and we'll take a look at it shortly.</p>
</div>
</body>
</html> | 10pockets | trunk/public/500.html | HTML | mit | 941 |
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require(File.join(File.dirname(__FILE__), 'config', 'boot'))
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'tasks/rails'
| 10pockets | trunk/Rakefile | Ruby | mit | 307 |
ActionController::Routing::Routes.draw do |map|
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# You can have the root of your site routed by hooking up ''
# -- just remember to delete public/index.html.
map.connect '', :controller => "account", :action => "index"
# Allow downloading Web Service WSDL as a file with an extension
# instead of a file named 'wsdl'
map.connect ':controller/service.wsdl', :action => 'wsdl'
# Install the default route as the lowest priority.
map.connect ':controller/:action/:id.:format'
map.connect ':controller/:action/:id'
end
| 10pockets | trunk/config/routes.rb | Ruby | mit | 985 |
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Enable the breakpoint server that script/breakpointer connects to
config.breakpoint_server = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_view.cache_template_extensions = false
config.action_view.debug_rjs = true
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
| 10pockets | trunk/config/environments/development.rb | Ruby | mit | 910 |
# Settings specified here will take precedence over those in config/environment.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Tell ActionMailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test | 10pockets | trunk/config/environments/test.rb | Ruby | mit | 853 |
# Settings specified here will take precedence over those in config/environment.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Full error reports are disabled and caching is turned on
config.action_controller.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
| 10pockets | trunk/config/environments/production.rb | Ruby | mit | 763 |
# Don't change this file. Configuration is done in config/environment.rb and config/environments/*.rb
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
unless defined?(Rails::Initializer)
if File.directory?("#{RAILS_ROOT}/vendor/rails")
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
else
require 'rubygems'
rails_gem_version =
if defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION
else
File.read("#{File.dirname(__FILE__)}/environment.rb") =~ /^[^#]*RAILS_GEM_VERSION\s+=\s+'([\d.]+)'/
$1
end
if rails_gem_version
rails_gem = Gem.cache.search('rails', "=#{rails_gem_version}.0").sort_by { |g| g.version.version }.last
if rails_gem
gem "rails", "=#{rails_gem.version.version}"
require rails_gem.full_gem_path + '/lib/initializer'
else
STDERR.puts %(Cannot find gem for Rails =#{rails_gem_version}.0:
Install the missing gem with 'gem install -v=#{rails_gem_version} rails', or
change environment.rb to define RAILS_GEM_VERSION with your desired version.
)
exit 1
end
else
gem "rails"
require 'initializer'
end
end
Rails::Initializer.run(:set_load_path)
end
| 10pockets | trunk/config/boot.rb | Ruby | mit | 1,246 |
# Be sure to restart your web server when you modify this file.
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '1.2.6' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here
# Skip frameworks you're not going to use (only works if using vendor/rails)
# config.frameworks -= [ :action_web_service, :action_mailer ]
# Only load the plugins named here, by default all plugins in vendor/plugins are loaded
# config.plugins = %W( exception_notification ssl_requirement )
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Use the database for sessions instead of the file system
# (create the session table with 'rake db:sessions:create')
# config.action_controller.session_store = :active_record_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc
# Add new inflection rules using the following format
# (all these examples are active by default):
# Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# See Rails::Configuration for more options
end
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register "application/x-mobile", :mobile
# Include your application configuration below
require 'gettext/rails'
require 'amazon/ecs'
Amazon::Ecs.debug = true
Amazon::Ecs.options = {
:aWS_access_key_id => "[your access key]",
:associate_tag => "[your associate tag]",
:country => :jp
}
require 'rakuten'
# RakutenWebService::DEVELOPER_ID = "[your developer id]"
| 10pockets | trunk/config/environment.rb | Ruby | mit | 2,706 |
require 'gettext/utils'
task :updatepo do
GetText.update_pofiles("10pockets", Dir.glob("{app,config,components,lib}/**/*.{rb,rhtml,rjs}"),
"10pockets 0.0.1"
)
end
task :makemo do
GetText.create_mofiles(true, "po", "locale")
end
| 10pockets | trunk/lib/tasks/gettext.rake | Ruby | mit | 283 |
require 'rexml/document'
require 'cgi'
require 'open-uri'
module RakutenWebService
DEVELOPER_ID = "[your developer id]"
module GenreSearch
class URL_Builder
attr_accessor :affiliateId, :callBack, :genreid, :genrepath
attr_accessor :base, :developerId, :operation, :version
def initialize(developerId = nil)
@base = "http://api.rakuten.co.jp/rws/1.11/rest?"
@operation = "GenreSearch"
@version = "2007-04-11"
@developerId = developerId
@genrepath = "0"
end
def build
url = @base
raise RuntimeError, 'No developerId' unless @developerId
raise RuntimeError, 'No GenreId' unless @genreid
@genreid = @genreid.to_s
url += "developerId=#{@developerId}"
url += "&operation=#{@operation}"
url += "&version=#{@version}"
url += "&affiliateId=#{affiliateId}" if @affiliateId
url += "&callBack=#{@callBack}" if @callBack
url += "&genreId=#{CGI.escape(@genreid)}" if @genreid
url += "&genrePath=#{CGI.escape(@genrepath)}" if @genrepath
end
end
class Result
attr_accessor :header, :genres
def initialize(url)
# get xml contents
xml = open(url).read
doc = REXML::Document.new xml
# create header
@header = RakutenWebService::GenreSearch::Result_Header.new
doc.elements["/Response/header:Header/Args"].each do |e|
@header.method((e.attributes["key"].downcase.gsub("-", "") + "=").to_sym).call(e.attributes["value"])
end
@header.status = doc.elements["/Response/header:Header/Status"].text
@header.statusmsg = doc.elements["/Response/header:Header/StatusMsg"].text
# create genre
@genres = {}
["parent", "current"].each do |n|
if doc.elements["/Response/Body/genreSearch:GenreSearch/#{n}"]
@genre = RakutenWebService::GenreSearch::Result_Genre.new
doc.elements["/Response/Body/genreSearch:GenreSearch/#{n}"].each do |i|
next unless i.name
@genre.method((i.name.downcase + "=").to_sym).call(i.text)
end
@genres[n] = @genre
end
end
end
end
class Result_Header
attr_accessor :useragent, :developerid, :apiversion, :operation, :version, :status, :statusmsg
attr_accessor :count, :page, :first, :last, :hits, :carrier, :pagecount
attr_accessor :sort, :availability, :field, :imageflag, :orflag, :keyword, :itemcode, :genreid, :genrepath
end
class Result_Genre
attr_accessor :genreid, :genrename, :genrelevel
end
end
module ItemCodeSearch
class Result
attr_accessor :header, :item
def initialize(url)
# get xml contents
xml = open(url).read
doc = REXML::Document.new xml
# create header
@header = RakutenWebService::Result_Header.new
doc.elements["/Response/header:Header/Args"].each do |e|
@header.method((e.attributes["key"].downcase.gsub("-", "") + "=").to_sym).call(e.attributes["value"])
end
@header.status = doc.elements["/Response/header:Header/Status"].text
@header.statusmsg = doc.elements["/Response/header:Header/StatusMsg"].text
# create items
@item = nil
if doc.elements["/Response/Body/itemCodeSearch:ItemCodeSearch/Item"]
@item = RakutenWebService::Result_Item.new
doc.elements["/Response/Body/itemCodeSearch:ItemCodeSearch/Item"].each do |i|
next unless i.name
@item.method((i.name.downcase + "=").to_sym).call(i.text)
end
end
end
end
class URL_Builder
attr_accessor :affiliateId, :callBack, :itemcode, :carrier
attr_accessor :base, :developerId, :operation, :version
def initialize(developerId = nil)
@base = "http://api.rakuten.co.jp/rws/1.11/rest?"
@operation = "ItemCodeSearch"
@version = "2007-04-11"
@developerId = developerId
end
def build
url = @base
raise RuntimeError, 'No developerId' unless @developerId
raise RuntimeError, 'No ItemCode' unless @itemcode
url += "developerId=#{@developerId}"
url += "&operation=#{@operation}"
url += "&version=#{@version}"
url += "&affiliateId=#{affiliateId}" if @affiliateId
url += "&callBack=#{@callBack}" if @callBack
url += "&itemCode=#{CGI.escape(@itemcode)}" if @itemcode
url
end
end
end
class Result_Header
attr_accessor :useragent, :developerid, :apiversion, :operation, :version, :status, :statusmsg
attr_accessor :count, :page, :first, :last, :hits, :carrier, :pagecount
attr_accessor :sort, :availability, :field, :imageflag, :orflag, :keyword, :itemcode
end
class Result_Item
attr_accessor :itemname, :itemcode, :itemprice, :itemcaption, :itemurl
attr_accessor :affiliateurl, :imageflag, :smallimageurl, :mediumimageurl
attr_accessor :availability, :taxflag, :postageflag, :creditcardflag
attr_accessor :shopoftheyearflag, :affiliaterate, :starttime, :endtime, :carrier
attr_accessor :reviewcount, :reviewaverage, :shopname, :shopcode, :shopurl, :genreid
end
module ItemSearch
class Result
attr_accessor :header, :items
def initialize(url)
# get xml contents
xml = open(url).read
doc = REXML::Document.new xml
# create header
@header = RakutenWebService::Result_Header.new
doc.elements["/Response/header:Header/Args"].each do |e|
@header.method((e.attributes["key"].downcase.gsub("-", "") + "=").to_sym).call(e.attributes["value"])
end
@header.status = doc.elements["/Response/header:Header/Status"].text
@header.statusmsg = doc.elements["/Response/header:Header/StatusMsg"].text
["count", "page", "first", "last", "hits", "carrier", "pageCount"].each do |n|
next unless doc.elements["/Response/Body/itemSearch:ItemSearch/#{n}"]
@header.method((n.downcase + "=").to_sym).call(doc.elements["/Response/Body/itemSearch:ItemSearch/#{n}"].text)
end
# create items
@items = []
if doc.elements["/Response/Body/itemSearch:ItemSearch/Items"]
doc.elements["/Response/Body/itemSearch:ItemSearch/Items"].each do |i|
next unless i
item = RakutenWebService::Result_Item.new
i.each do |e|
next unless e.name
item.method((e.name.downcase + "=").to_sym).call(e.text)
end
@items << item
end
end
end
end
class URL_Builder
attr_accessor :affiliateId, :callBack, :keyword, :shopCode, :genreId
attr_accessor :catalogCode, :minPrice, :maxPrice, :ngkeyword, :genreInformationFlag
attr_accessor :base, :developerId, :operation, :hits, :page, :availability, :sort, :version
attr_accessor :availability, :field, :carrier, :imageFlag, :orFlag, :base
def initialize(developerId = nil)
@base = "http://api.rakuten.co.jp/rws/1.11/rest?"
@operation = "ItemSearch"
@version = "2007-10-25"
@sort = CGI.escape "+itemPrice"
@developerId = developerId
@hits = 30
@page = 1
@availability = @field = @carrier = @imageFlag = @orFlag = 0
end
def build
url = @base
raise RuntimeError, 'No developerId' unless @developerId
url += "developerId=#{@developerId}"
url += "&operation=#{@operation}"
url += "&version=#{@version}"
url += "&affiliateId=#{affiliateId}" if @affiliateId
url += "&callBack=#{@callBack}" if @callBack
url += "&keyword=#{CGI.escape(@keyword)}" if @keyword
url += "&shopCode=#{shopCode}" if @shopCode
url += "&genreId=#{genreId}" if @genreId
url += "&catalogCode=#{@catalogCode}" if @catalogCode
url += "&hits=#{@hits}" if @hits
url += "&page=#{@page}" if @page
url += "&sort=#{@sort}" if @sort
url += "&minPrice=#{@minPrice}" if @minPrice
url += "&maxPrice=#{@maxPrice}" if @maxPrice
url += "&availability=#{@availability}" if @availability
url += "&field=#{@field}" if @field
url += "&carrier=#{@carrier}" if @carrier
url += "&imageFlag=#{@imageFlag}" if @imageFlag
url += "&orFlag=#{@orFlag}" if @orFlag
url += "&NGKeyword=#{CGI.escape(@ngkeyword)}" if @ngkeyword
url += "&genreInformationFlag=#{@genreInformationFlag}" if @genreInformationFlag
url
end
end
end
end
if __FILE__ == $0
developerId = RakutenWebService::DEVELOPER_ID
url = RakutenWebService::ItemSearch::URL_Builder.new developerId
url.keyword = "カラーボックス"
rakuten = RakutenWebService::ItemSearch::Result.new url.build
p rakuten.header.keyword
rakuten.items.each do |i|
p i.itemname
end
url = RakutenWebService::ItemCodeSearch::URL_Builder.new developerId
url.itemcode = "kami-bungu:1392578"
rakuten = RakutenWebService::ItemCodeSearch::Result.new url.build
p rakuten.item.itemname
url = RakutenWebService::GenreSearch::URL_Builder.new developerId
url.genreid = "111202"
rakuten = RakutenWebService::GenreSearch::Result.new url.build
p rakuten.genres['current'].genrename
end
| 10pockets | trunk/lib/rakuten.rb | Ruby | mit | 9,408 |
require_dependency "user"
module OpenidLoginSystem
protected
# overwrite this if you want to restrict access to only a few actions
# or if you want to check if the user has the correct rights
# example:
#
# # only allow nonbobs
# def authorize?(user)
# user.login != "bob"
# end
def authorize?(user)
true
end
# overwrite this method if you only want to protect certain actions of the controller
# example:
#
# # don't protect the login and the about method
# def protect?(action)
# if ['action', 'about'].include?(action)
# return false
# else
# return true
# end
# end
def protect?(action)
true
end
# login_required filter. add
#
# before_filter :login_required
#
# if the controller should be under any rights management.
# for finer access control you can overwrite
#
# def authorize?(user)
#
def login_required
if not protect?(action_name)
return true
end
if @session[:user_id] and authorize?(User.find(@session[:user_id]))
return true
end
# store current location so that we can
# come back after the user logged in
store_location
# call overwriteable reaction to unauthorized access
access_denied
return false
end
# overwrite if you want to have special behavior in case the user is not authorized
# to access the current operation.
# the default action is to redirect to the login screen
# example use :
# a popup window might just close itself for instance
def access_denied
redirect_to :controller=>"/account", :action =>"login"
end
# store current uri in the session.
# we can return to this location by calling return_location
def store_location
@session[:return_to] = @request.request_uri
end
# move to the last store_location call or to the passed default one
def redirect_back_or_default(default)
if @session[:return_to].nil?
redirect_to default
else
redirect_to_url @session[:return_to]
@session[:return_to] = nil
end
end
end
| 10pockets | trunk/lib/openid_login_system.rb | Ruby | mit | 2,120 |
JEU = graphique
#JEU =texte
OPT= -Wall -pedantic -ansi
DBG=-ggdb
CC=gcc
ifeq ($(JEU),texte)
SRCS = CARTE.c JOUEUR.c JEU.c CASE.c DE.c main.c NCURSE.c PION.c
LIBS = -lm -lncurses
EXEC_NAME = 1001-Questions_texte
else
SRCS = CARTE.c JOUEUR.c JEU.c CASE.c DE.c main.c SDL.c PION.c
LIBS = -lm -lSDL -lSDL_ttf -lSDL_image
EXEC_NAME = 1001-Questions
endif
BIN_DIR=bin
SRC_DIR=src
OBJ_DIR=obj
DATA_DIR=data
jouer : $(BIN_DIR)/$(EXEC_NAME)
$(BIN_DIR)/$(EXEC_NAME) : $(SRCS:%c=$(OBJ_DIR)/%o)
$(CC) -o $@ $^ $(LIBS)
$(OBJ_DIR)/%o: $(SRC_DIR)/%c
$(CC) $(OPT) -c $< -o $@
objets : $(SRCS:%c=$(OBJ_DIR)/%o)
$(OBJ_DIR)/%o: $(SRC_DIR)/%c
$(CC) $(OPT) -c $< -o $@
clean :
rm $(OBJ_DIR)/*.o
| 1001-questions | trunk/Makefile | Makefile | gpl2 | 715 |
/**
@brief 1001-Questions <br>Permet de créer les cartes de jeu
@author Gaudillat Flavien
@file DE.h
@version 1.0
@date 2013/12/10
*/
#ifndef DE_H
#define DE_H
/**
\struct DE
@brief Module des dés de jeu
*/
typedef struct
{
int de1;
int de2;
} DE;
/**
@brief Création des dés
@return DE
*/
DE* deCreer_De();
/**
@brief Tirage Aléatoire des dés
@param [in,out] d
@return none
*/
void deTirage_Alea(DE* d);
/**
@brief Libere l'espace alloué pour la struct DE
@param [in,out] d
@return none
*/
void deLibere_De(DE* d);
#endif
| 1001-questions | trunk/src/DE.h | C | gpl2 | 546 |
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "PION.h"
PION* piCreer_Pion()
{
PION* pi=(PION*) malloc(sizeof(PION));
pi->jo = joCreer_Joueur();
strcpy (pi->nom, "");
pi->x_dep1 = 2;
pi->y_dep1 = 1;
pi->x_dep2 = 2;
pi->y_dep2 = 1;
pi->x_dep3 = 2;
pi->y_dep3 = 1;
pi->x_dep4 = 2;
pi->y_dep4 = 1;
pi->numcase=1;
return pi;
}
void piLibere_Pion(PION *pi)
{
free (pi);
}
void piTest_Pion()
{
PION *pi;
pi = piCreer_Pion();
printf("Tests du module pion : \n\n") ;
/* Début du test de piCreer_Pion*/
printf("Test de piCreer_Pion ... \n") ;
assert(pi->numcase == 1);
assert(strcmp(pi->nom, "")==0);
free(pi);
printf("Tests du module Pion terminé \n\n") ;
}
| 1001-questions | trunk/src/PION.c | C | gpl2 | 791 |
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "time.h"
#include "string.h"
#include "CARTE.h"
#include "CASE.h"
#include "JEU.h"
JEUCARTES carCreer_Carte()
{
JEUCARTES tabcarte = (CARTE*)malloc(24*sizeof(CARTE));
/*Les cartes Questions*/
strcpy(tabcarte[Mcar1].type,"Question");
strcpy(tabcarte[Mcar1].consigne, "Quel est la capital de la France ?");
strcpy(tabcarte[Mcar2].type,"Question");
strcpy(tabcarte[Mcar2].consigne,"Quel est le champion en titre de l1 ?");
strcpy(tabcarte[Mcar3].type,"Question");
strcpy(tabcarte[Mcar3].consigne,"Combien y'a t-il de joueurs sur un terrain de handball ?");
strcpy(tabcarte[Mcar4].type,"Question");
strcpy(tabcarte[Mcar4].consigne,"Quel est le mot en nglis pour bonjour ?");
strcpy(tabcarte[Mcar5].type,"Question");
strcpy(tabcarte[Mcar5].consigne,"Citez 4 espèces différentes de mamifères.");
strcpy(tabcarte[Mcar6].type,"Question");
strcpy(tabcarte[Mcar6].consigne,"Combien de point faut-il pour avoir son permis ?");
strcpy(tabcarte[Mcar7].type,"Question");
strcpy(tabcarte[Mcar7].consigne,"Combien fais 12 fois 12 ?");
strcpy(tabcarte[Mcar8].type,"Question");
strcpy(tabcarte[Mcar8].consigne,"Combien y'a t'il de Region en France ?");
/*Les cartes référent pédagogique*/
strcpy(tabcarte[RPcar1].type,"pièges");
strcpy(tabcarte[RPcar1].consigne,"vous gagné 10 points.");
strcpy(tabcarte[RPcar2].type,"pièges");
strcpy(tabcarte[RPcar2].consigne,"Tirer une question.");
strcpy(tabcarte[RPcar3].type,"pièges");
strcpy(tabcarte[RPcar3].consigne,"Vous perdez 10 points.");
strcpy(tabcarte[RPcar4].type,"pièges");
strcpy(tabcarte[RPcar4].consigne,"Retournez a la case départ.");
strcpy(tabcarte[RPcar5].type,"pièges");
strcpy(tabcarte[RPcar5].consigne,"aller la dernière question.");
return tabcarte;
}
void carLibere_Carte(JEUCARTES *car)
{
int i;
for (i=0; i<24; i++)
{
free (car[i]);
}
}
void carTestCarte()
{
JEUCARTES car;
int i;
car = carCreer_Carte();
printf("Tests du module CARTE : \n\n") ;
/* Début du test de caCreer_Case*/
printf("Test de caCreer_Case ... \n") ;
for(i=0; i<=24; i++)
{
assert(strcmp(car[i].type,"")==1);
}
carLibere_Carte(&car);
printf("Tests du module CASE terminé \n\n") ;
}
| 1001-questions | trunk/src/CARTE.c | C | gpl2 | 2,515 |
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "JOUEUR.h"
#include "JEU.h"
int joNombre_Joueur()
{
int nbjoueur = 0;
printf("Combien de joueur veulent jouer ?\n");
scanf ("%d", &nbjoueur);
return nbjoueur;
}
TABJOUEUR joCreer_Joueur()
{
int i;
int nbjoueur = joNombre_Joueur();
TABJOUEUR jo = (JOUEUR*) malloc(nbjoueur*sizeof(JOUEUR));
for (i=0; i<nbjoueur; i++)
{
jo[i].point = 0;
strcpy(jo[i].nom, "");
}
return jo;
}
void joRentrer_Nom(TABJOUEUR * jo, int nbjoueur)
{
int i;
for (i=0; i<nbjoueur; i++)
{
printf("donnner votre nom\n");
scanf("%s", jo[i]->nom);
printf("votre nom est %s\n", jo[i]->nom);
jo[i]->point=100;
}
}
void joLibere_Joueur(TABJOUEUR *jo, int nbjoueur)
{
int i;
for (i=0; i<nbjoueur; i++)
{
free(jo[i]);
}
}
void piTest_Joueur()
{
TABJOUEUR jo;
jo = joCreer_Joueur();
int nb,i;
printf("Tests du module joueur : \n\n") ;
/* Début du test de joNombre_Joueur*/
printf("Test de joNombre_Joueur ... \n") ;
nb = joNombre_Joueur();
assert(nb!=0);
/* Début du test de joCreer_Joueur*/
printf("Test de joCreer_Joueur ... \n") ;
for (i=0; i<nb; i++)
{
assert(strcmp(jo[i].nom, "")==0);
assert(jo[i].point==0);
}
/* Début du test de joRentrer_Nom*/
printf("Test de joRentrer_Nom ... \n") ;
for (i=0; i<nb; i++)
{
assert(strcmp(jo[i].nom, "")==1);
}
joLibere_Joueur(&jo,nb);
printf("Tests du module Pion terminé \n\n") ;
}
| 1001-questions | trunk/src/JOUEUR.c | C | gpl2 | 1,622 |
/**
@brief 1001-Questions <br>Permet de créer les cartes de jeu
@author Gaudillat Flavien
@file CARTE.h
@version 1.0
@date 2013/12/10
*/
#ifndef CARTE_H
#define CARTE_H
#include "CASE.h"
#include "PION.h"
/**
\struct CARTE
@brief Module des cartes de jeu
*/
typedef struct
{
char type[32];
char consigne[150];
} CARTE;
typedef CARTE* JEUCARTES;
typedef enum { Mcar1=0, Mcar2, Mcar3, Mcar4, Mcar5, Mcar6, Mcar7, Mcar8,
RPcar1, RPcar2, RPcar3, RPcar4, RPcar5 } NUMCARTE;
/**
@brief Initialisation des cartes de jeu
@param [in,out] car
@return none
*/
JEUCARTES carCreer_Carte();
/**
@brief libère l'espace alloué pour la struct CARTE
@param [in,out] car
@return none
*/
void carLibere_Carte(JEUCARTES *car);
/**
@brief Test de regression pour la struct CARTE
@param [in,out] none
@return none
*/
void carTestCarte();
#endif
| 1001-questions | trunk/src/CARTE.h | C | gpl2 | 860 |
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "JEU.h"
void jeInit_Jeu(JEU* je)
{
je->de=deCreer_De();
je->pi=piCreer_Pion();
je->ta=caCreer_Case();
je->tabcarte=carCreer_Carte();
je->avancement=0;
je->nbjoueur=0;
je->d = 0;
je->respi=0;
je->resqu=0;
je->reponse=0;
}
void jeRecup_Des(JEU* je)
{
int de;
assert (je!=NULL);
deTirage_Alea(je->de);
de = je->de->de1 + je->de->de2;
je->d = de;
}
void jeDeplacement_Pion1(JEU* je)
{
if(je->pi->numcase>39)
{
je->pi->numcase = 0;
}
printf("le pion est sur la case %d \n",je->pi->numcase);
je->pi->numcase = je->pi->numcase + je->d;
je->pi->x_dep1 = je->ta[je->pi->numcase].x;
je->pi->y_dep2 = je->ta[je->pi->numcase].y;
printf("le pion est sur la case de coordonner x %f \n",je->pi->x_dep1);
printf("le pion est sur la case de coordonner y %f \n",je->pi->y_dep1);
}
void jeDeplacement_Pion2(JEU* je)
{
if(je->pi->numcase>39)
{
je->pi->numcase = 0;
}
printf("le pion est sur la case %d \n",je->pi->numcase);
je->pi->numcase = je->pi->numcase + je->d;
je->pi->x_dep2 = je->ta[je->pi->numcase].x;
je->pi->y_dep2 = je->ta[je->pi->numcase].y;
printf("le pion est sur la case de coordonner x %f \n",je->pi->x_dep2);
printf("le pion est sur la case de coordonner y %f \n",je->pi->y_dep2);
}
void jeDeplacement_Pion3(JEU* je)
{
if(je->pi->numcase>39)
{
je->pi->numcase = 0;
}
printf("le pion est sur la case %d \n",je->pi->numcase);
je->pi->numcase = je->pi->numcase + je->d;
je->pi->x_dep3 = je->ta[je->pi->numcase].x;
je->pi->y_dep3 = je->ta[je->pi->numcase].y;
printf("le pion est sur la case de coordonner x %f \n",je->pi->x_dep3);
printf("le pion est sur la case de coordonner y %f \n",je->pi->y_dep3);
}
void jeDeplacement_Pion4(JEU* je)
{
if(je->pi->numcase>39)
{
je->pi->numcase = 0;
}
printf("le pion est sur la case %d \n",je->pi->numcase);
je->pi->numcase = je->pi->numcase + je->d;
je->pi->x_dep4 = je->ta[je->pi->numcase].x;
je->pi->y_dep4 = je->ta[je->pi->numcase].y;
printf("le pion est sur la case de coordonner x %f \n",je->pi->x_dep4);
printf("le pion est sur la case de coordonner y %f \n",je->pi->y_dep4);
}
void jeReponse_question(JEU* je)
{
int i;
printf("la reponse donné est elle juste, 1 pour oui 0 pour non \n");
scanf("%d", &i);
if (i == 1) je->reponse = 1;
else je->reponse = 0;
}
void jeActualise_point(JEU* je)
{
if(je->reponse == 1)
{
je->pi->jo->point = je->pi->jo->point + 10;
}
else je->pi->jo->point = je->pi->jo->point - 10;
}
void jeTirage_Carte(JEU* je)
{
int res_ques=(rand() % (8) + 1);
int res_pi=(rand() % (13) + 9);
if (strcmp(je->ta->type, "Question")==0)
{
if (res_ques==1)
{
printf("quel est la capital de la france ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==2)
{
printf("quel est le champion en titre de L1 ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==3)
{
printf("Combien y'a t'il de joueur sur un terrain de handball ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==4)
{
printf("quel est le mot en anglais pour bonjour ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==5)
{
printf("citez 4 espèces differentes de mamifère ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==6)
{
printf("Combien faut il de point pour avoir son permis ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==7)
{
printf("Combien font 12 fois 12 ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==8)
{
printf("Combien ya t'il de Region en France ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
}
if (strcmp(je->ta->type,"pièges")==0)
{
if (res_pi==9)
{
je->pi->jo->point = je->pi->jo->point + 10;
}
else if (res_pi==10)
{
if (strcmp(je->ta->type, "Question")==0)
{
if (res_ques==1)
{
printf("quel est la capital de la france ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==2)
{
printf("quel est le champion en titre de L1 ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==3)
{
printf("Combien y'a t'il de joueur sur un terrain de handball ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==4)
{
printf("quel est le mot en anglais pour bonjour ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==5)
{
printf("citez 4 espèces differentes de mamifère ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==6)
{
printf("Combien faut il de point pour avoir son permis ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==7)
{
printf("Combien font 12 fois 12 ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
else if (res_ques==8)
{
printf("Combien ya t'il de Region en France ?\n");
jeReponse_question(je);
jeActualise_point(je);
}
}
}
else if (res_pi==11)
{
je->pi->jo->point = je->pi->jo->point - 10;
}
else if (res_pi==12)
{
je->pi->numcase = 1;
}
else if (res_pi==13)
{
je->pi->numcase = 55;
}
}
je->respi=res_pi;
je->resqu=res_ques;
}
| 1001-questions | trunk/src/JEU.c | C | gpl2 | 6,089 |
#include "SDL.h"
const int TAILLE_SPRITE=32;
void sdljeuInit(SDLJEU *pSdlJeu)
{
JEU *jeu;
TTF_Init();
jeu = &(pSdlJeu->jeu);
jeInit_Jeu(jeu);
assert( SDL_Init( SDL_INIT_EVERYTHING )!= -1 );
pSdlJeu->ecran = SDL_SetVideoMode(1300, 1200, 32, SDL_SWSURFACE );
assert( pSdlJeu->ecran!=NULL);
SDL_WM_SetCaption( "1001-Questions", NULL );
pSdlJeu->surface_Menu = IMG_Load("data/Menu.jpg");
if (pSdlJeu->surface_Menu==NULL)
pSdlJeu->surface_Menu = IMG_Load("data/Menu.jpg");
assert( pSdlJeu->surface_Menu!=NULL);
pSdlJeu->surface_MenuJoueur = IMG_Load("data/MenuJoueur.jpg");
if (pSdlJeu->surface_MenuJoueur==NULL)
pSdlJeu->surface_MenuJoueur = IMG_Load("data/MenuJoueur.jpg");
assert( pSdlJeu->surface_MenuJoueur!=NULL);
pSdlJeu->surface_PlateauFinal = IMG_Load("data/plateau.jpg");
if (pSdlJeu->surface_PlateauFinal==NULL)
pSdlJeu->surface_PlateauFinal = IMG_Load("data/plateau.jpg");
assert( pSdlJeu->surface_PlateauFinal!=NULL);
pSdlJeu->surface_Mcar1 = IMG_Load("data/Mcar1.jpg");
if (pSdlJeu->surface_Mcar1==NULL)
pSdlJeu->surface_Mcar1 = IMG_Load("data/Mcar1.jpg");
assert( pSdlJeu->surface_Mcar1!=NULL);
pSdlJeu->surface_Mcar2 = IMG_Load("data/Mcar2.jpg");
if (pSdlJeu->surface_Mcar2==NULL)
pSdlJeu->surface_Mcar2 = IMG_Load("data/Mcar2.jpg");
assert( pSdlJeu->surface_Mcar2!=NULL);
pSdlJeu->surface_Mcar3 = IMG_Load("data/Mcar3.jpg");
if (pSdlJeu->surface_Mcar3==NULL)
pSdlJeu->surface_Mcar3 = IMG_Load("data/Mcar3.jpg");
assert( pSdlJeu->surface_Mcar3!=NULL);
pSdlJeu->surface_Mcar4 = IMG_Load("data/Mcar4.jpg");
if (pSdlJeu->surface_Mcar4==NULL)
pSdlJeu->surface_Mcar4 = IMG_Load("data/Mcar4.jpg");
assert( pSdlJeu->surface_Mcar4!=NULL);
pSdlJeu->surface_Mcar5 = IMG_Load("data/Mcar5.jpg");
if (pSdlJeu->surface_Mcar5==NULL)
pSdlJeu->surface_Mcar5 = IMG_Load("data/Mcar5.jpg");
assert( pSdlJeu->surface_Mcar5!=NULL);
pSdlJeu->surface_Mcar6 = IMG_Load("data/Mcar6.jpg");
if (pSdlJeu->surface_Mcar6==NULL)
pSdlJeu->surface_Mcar6 = IMG_Load("data/Mcar6.jpg");
assert( pSdlJeu->surface_Mcar6!=NULL);
pSdlJeu->surface_Mcar7 = IMG_Load("data/Mcar7.jpg");
if (pSdlJeu->surface_Mcar7==NULL)
pSdlJeu->surface_Mcar7 = IMG_Load("data/Mcar7.jpg");
assert( pSdlJeu->surface_Mcar7!=NULL);
pSdlJeu->surface_Mcar8 = IMG_Load("data/Mcar8.jpg");
if (pSdlJeu->surface_Mcar8==NULL)
pSdlJeu->surface_Mcar8 = IMG_Load("data/Mcar8.jpg");
assert( pSdlJeu->surface_Mcar8!=NULL);
pSdlJeu->surface_RPcar1 = IMG_Load("data/RPcar1.jpg");
if (pSdlJeu->surface_RPcar1==NULL)
pSdlJeu->surface_RPcar1 = IMG_Load("data/RPcar1.jpg");
assert( pSdlJeu->surface_RPcar1!=NULL);
pSdlJeu->surface_RPcar2 = IMG_Load("data/RPcar2.jpg");
if (pSdlJeu->surface_RPcar2==NULL)
pSdlJeu->surface_RPcar2 = IMG_Load("data/RPcar2.jpg");
assert( pSdlJeu->surface_RPcar2!=NULL);
pSdlJeu->surface_RPcar3 = IMG_Load("data/RPcar3.jpg");
if (pSdlJeu->surface_RPcar3==NULL)
pSdlJeu->surface_RPcar3 = IMG_Load("data/RPcar3.jpg");
assert( pSdlJeu->surface_RPcar3!=NULL);
pSdlJeu->surface_RPcar4 = IMG_Load("data/RPcar4.jpg");
if (pSdlJeu->surface_RPcar4==NULL)
pSdlJeu->surface_RPcar4 = IMG_Load("data/RPcar4.jpg");
assert( pSdlJeu->surface_RPcar4!=NULL);
pSdlJeu->surface_RPcar5 = IMG_Load("data/RPcar5.jpg");
if (pSdlJeu->surface_RPcar5==NULL)
pSdlJeu->surface_RPcar5 = IMG_Load("data/RPcar5.jpg");
assert( pSdlJeu->surface_RPcar5!=NULL);
pSdlJeu->surface_regle1 = IMG_Load("data/Règle1.jpg");
if (pSdlJeu->surface_regle1==NULL)
pSdlJeu->surface_regle1 = IMG_Load("data/Règle1.jpg");
assert( pSdlJeu->surface_regle1!=NULL);
pSdlJeu->surface_regle2 = IMG_Load("data/Règle2.jpg");
if (pSdlJeu->surface_regle2==NULL)
pSdlJeu->surface_regle2 = IMG_Load("data/Règle2.jpg");
assert( pSdlJeu->surface_regle2!=NULL);
pSdlJeu->surface_1 = IMG_Load("data/pion1.jpg");
if (pSdlJeu->surface_1==NULL)
pSdlJeu->surface_1 = IMG_Load("data/pion1.jpg");
assert( pSdlJeu->surface_1!=NULL);
pSdlJeu->surface_2 = IMG_Load("data/pion2.jpg");
if (pSdlJeu->surface_2==NULL)
pSdlJeu->surface_2= IMG_Load("data/pion2.jpg");
assert( pSdlJeu->surface_2!=NULL);
pSdlJeu->surface_3 = IMG_Load("data/pion3.jpg");
if (pSdlJeu->surface_3==NULL)
pSdlJeu->surface_3 = IMG_Load("data/pion3.jpg");
assert( pSdlJeu->surface_3!=NULL);
pSdlJeu->surface_4 = IMG_Load("data/pion4.jpg");
if (pSdlJeu->surface_4==NULL)
pSdlJeu->surface_4 = IMG_Load("data/pion4.jpg");
assert( pSdlJeu->surface_4!=NULL);
}
void sdlAff_Carte(SDLJEU *pSdlJeu)
{
SDL_Rect carte, carte2;
carte.x = 0;
carte.y = 0;
carte.h = 200;
carte.w = 400;
carte2.x = 10;
carte2.y = 10;
carte2.h = 200;
carte2.w = 400;
if(pSdlJeu->jeu.resqu == 1)
{
SDL_BlitSurface(pSdlJeu->surface_Mcar1,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.resqu == 2)
{
SDL_BlitSurface(pSdlJeu->surface_Mcar2,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.resqu == 3)
{
SDL_BlitSurface(pSdlJeu->surface_Mcar3,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.resqu == 4)
{
SDL_BlitSurface(pSdlJeu->surface_Mcar4,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.resqu == 5)
{
SDL_BlitSurface(pSdlJeu->surface_Mcar5,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.resqu == 6)
{
SDL_BlitSurface(pSdlJeu->surface_Mcar6,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.resqu == 7)
{
SDL_BlitSurface(pSdlJeu->surface_Mcar7,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.resqu == 8)
{
SDL_BlitSurface(pSdlJeu->surface_Mcar8,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.respi == 13)
{
SDL_BlitSurface(pSdlJeu->surface_RPcar1,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.respi == 14)
{
SDL_BlitSurface(pSdlJeu->surface_RPcar2,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.respi == 15)
{
SDL_BlitSurface(pSdlJeu->surface_RPcar3,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.respi == 16)
{
SDL_BlitSurface(pSdlJeu->surface_RPcar4,&carte,pSdlJeu->ecran,&carte2);
}
if(pSdlJeu->jeu.respi == 17)
{
SDL_BlitSurface(pSdlJeu->surface_RPcar5,&carte,pSdlJeu->ecran,&carte2);
}
}
void sdlAff_1(SDLJEU *pSdlJeu)
{
SDL_Rect pion1, pion12;
pion1.x = 0;
pion1.y = 0;
pion1.h = 86;
pion1.w = 318;
pion12.x= pSdlJeu->jeu.pi->x_dep1;
pion12.y = pSdlJeu->jeu.pi->y_dep1;
pion12.h = 86;
pion12.w = 318;
SDL_BlitSurface(pSdlJeu->surface_1,&pion1,pSdlJeu->ecran,&pion12);
}
void sdlAff_2(SDLJEU *pSdlJeu)
{
SDL_Rect pion2, pion22;
pion2.x = 0;
pion2.y = 0;
pion2.h = 105;
pion2.w = 200;
pion22.x = pSdlJeu->jeu.pi->x_dep2;
pion22.y = pSdlJeu->jeu.pi->y_dep2;
pion22.h = 105;
pion22.w = 200;
SDL_BlitSurface(pSdlJeu->surface_2,&pion2,pSdlJeu->ecran,&pion22);
}
void sdlAff_3(SDLJEU *pSdlJeu)
{
SDL_Rect pion3, pion32;
pion3.x = 0;
pion3.y = 0;
pion3.h = 114;
pion3.w = 200;
pion32.x = pSdlJeu->jeu.pi->x_dep3;
pion32.y = pSdlJeu->jeu.pi->y_dep3;
pion32.h = 114;
pion32.w = 200;
SDL_BlitSurface(pSdlJeu->surface_3,&pion3,pSdlJeu->ecran,&pion32);
}
void sdlAff_4(SDLJEU *pSdlJeu)
{
SDL_Rect pion4, pion42;
pion4.x = 0;
pion4.y = 0;
pion4.h = 74;
pion4.w = 154;
pion42.x = pSdlJeu->jeu.pi->x_dep4;
pion42.y = pSdlJeu->jeu.pi->y_dep4;
pion42.h = 74;
pion42.w = 154;
SDL_BlitSurface(pSdlJeu->surface_4,&pion4,pSdlJeu->ecran,&pion42);
}
void sdlAff_De(SDLJEU *pSdlJeu)
{
char tab_de[4];
SDL_Rect position;
SDL_Color couleurNoire = {0, 0, 0};
TTF_Font *police = TTF_OpenFont("data/POLICE.TTF",50);
sprintf(tab_de,"%d",pSdlJeu->jeu.d);
pSdlJeu->de = TTF_RenderText_Blended(police, tab_de, couleurNoire);
position.x = 1174;
position.y = 13;
SDL_BlitSurface(pSdlJeu->de,NULL,pSdlJeu->ecran,&position);
}
void sdlAff_Score(SDLJEU *pSdlJeu)
{
int score1, score2, score3, score4;
char tab_score1[4];
char tab_score2[4];
char tab_score3[4];
char tab_score4[4];
SDL_Rect position;
SDL_Rect position2;
SDL_Rect position3;
SDL_Rect position4;
SDL_Color couleurNoire = {0, 0, 0};
TTF_Font *police = TTF_OpenFont("data/POLICE.TTF",50);
score1 = 10;
score2 = 10;
score3 = 10;
score4 = 10;
sprintf(tab_score1,"%d",score1);
sprintf(tab_score2,"%d",score2);
sprintf(tab_score3,"%d",score3);
sprintf(tab_score4,"%d",score4);
pSdlJeu->score1 = TTF_RenderText_Blended(police, tab_score1, couleurNoire);
pSdlJeu->score2 = TTF_RenderText_Blended(police, tab_score2, couleurNoire);
pSdlJeu->score3 = TTF_RenderText_Blended(police, tab_score3, couleurNoire);
pSdlJeu->score4 = TTF_RenderText_Blended(police, tab_score4, couleurNoire);
position.x = 500;
position.y = 10;
position2.x = 1173;
position2.y = 250;
position3.x = 500;
position3.y = 630;
position4.x = 39;
position4.y = 250;
SDL_BlitSurface(pSdlJeu->score1,NULL,pSdlJeu->ecran,&position);
SDL_BlitSurface(pSdlJeu->score2,NULL,pSdlJeu->ecran,&position2);
SDL_BlitSurface(pSdlJeu->score3,NULL,pSdlJeu->ecran,&position3);
SDL_BlitSurface(pSdlJeu->score4,NULL,pSdlJeu->ecran,&position4);
}
void sdljeuAff(SDLJEU *pSdlJeu)
{
SDL_Rect position;
SDL_FillRect( pSdlJeu->ecran, &pSdlJeu->ecran->clip_rect, SDL_MapRGB( pSdlJeu->ecran->format, 0xFF, 0xFF, 0xFF ) );
position.x = 0;
position.y = 0;
position.h = 1169;
position.w = 829;
if(pSdlJeu->jeu.avancement == 0)
{
SDL_BlitSurface(pSdlJeu->surface_Menu,&position,pSdlJeu->ecran,&position);
}
else if(pSdlJeu->jeu.avancement == 10)
{
SDL_BlitSurface(pSdlJeu->surface_regle1,&position,pSdlJeu->ecran,&position);
}
else if(pSdlJeu->jeu.avancement == 11)
{
SDL_BlitSurface(pSdlJeu->surface_regle2,&position,pSdlJeu->ecran,&position);
}
else if(pSdlJeu->jeu.avancement == 2)
{
SDL_BlitSurface(pSdlJeu->surface_MenuJoueur,&position,pSdlJeu->ecran,&position);
}
else if(pSdlJeu->jeu.avancement == 3)
{
SDL_BlitSurface(pSdlJeu->surface_PlateauFinal,&position,pSdlJeu->ecran,&position);
sdlAff_1(pSdlJeu);
sdlAff_2(pSdlJeu);
sdlAff_3(pSdlJeu);
sdlAff_4(pSdlJeu);
sdlAff_Score(pSdlJeu);
}
else if(pSdlJeu->jeu.avancement == 4)
{
SDL_BlitSurface(pSdlJeu->surface_PlateauFinal,&position,pSdlJeu->ecran,&position);
sdlAff_1(pSdlJeu);
sdlAff_2(pSdlJeu);
sdlAff_3(pSdlJeu);
sdlAff_4(pSdlJeu);
sdlAff_Score(pSdlJeu);
sdlAff_De(pSdlJeu);
}
else if(pSdlJeu->jeu.avancement == 5)
{
SDL_BlitSurface(pSdlJeu->surface_PlateauFinal,&position,pSdlJeu->ecran,&position);
sdlAff_3(pSdlJeu);
sdlAff_Score(pSdlJeu);
sdlAff_De(pSdlJeu);
pSdlJeu->jeu.avancement = 3;
}
else if(pSdlJeu->jeu.avancement == 6)
{
SDL_BlitSurface(pSdlJeu->surface_PlateauFinal,&position,pSdlJeu->ecran,&position);
sdlAff_2(pSdlJeu);
sdlAff_Score(pSdlJeu);
sdlAff_De(pSdlJeu);
pSdlJeu->jeu.avancement = 3;
}
else if(pSdlJeu->jeu.avancement == 7)
{
SDL_BlitSurface(pSdlJeu->surface_PlateauFinal,&position,pSdlJeu->ecran,&position);
sdlAff_4(pSdlJeu);
sdlAff_Score(pSdlJeu);
sdlAff_De(pSdlJeu);
pSdlJeu->jeu.avancement = 3;
}
else if(pSdlJeu->jeu.avancement == 8)
{
SDL_BlitSurface(pSdlJeu->surface_PlateauFinal,&position,pSdlJeu->ecran,&position);
sdlAff_4(pSdlJeu);
sdlAff_Score(pSdlJeu);
sdlAff_De(pSdlJeu);
pSdlJeu->jeu.avancement = 3;
}
else if(pSdlJeu->jeu.avancement == 9)
{
SDL_BlitSurface(pSdlJeu->surface_PlateauFinal,&position,pSdlJeu->ecran,&position);
sdlAff_Carte(pSdlJeu);
}
}
void sdljeuBoucle(SDLJEU *pSdlJeu)
{
SDL_Event event;
int continue_boucle = 1;
int numcase3=1;
int numcase4=1;
int numcase2=1;
int numcase1=1;
/* Horloges (en secondes)*/
float horloge_courante, horloge_precedente;
/* Intervalle de temps (en secondes) entre deux évolutions du jeu
//! Changer la valeur pour ralentir ou accélérer le déplacement des fantomes*/
float intervalle_horloge = 0.1f;
int rafraichissement;
sdljeuAff(pSdlJeu);
assert( SDL_Flip( pSdlJeu->ecran )!=-1 );
/* Récupère l'horloge actuelle et la convertit en secondes
//! clock() retourne le nombre de tops horloge depuis le lancement du programme*/
horloge_precedente = (float)clock()/(float)CLOCKS_PER_SEC;
/* Tant que ce n'est pas la fin ...*/
while ( continue_boucle == 1 )
{
rafraichissement = 0;
/*Récupère l'horloge actuelle et la convertit en secondes*/
horloge_courante = (float)clock()/(float)CLOCKS_PER_SEC;
/* Si suffisamment de temps s'est écoulé depuis la dernière prise d'horloge*/
if (horloge_courante-horloge_precedente>=intervalle_horloge)
{
rafraichissement = 1;
horloge_precedente = horloge_courante;
}
/* tant qu'il y a des evenements à traiter : cette boucle n'est pas bloquante*/
while ( SDL_PollEvent( &event ) )
{
/* Si l'utilisateur a cliqué sur la croix de fermeture*/
if ( event.type == SDL_QUIT )
continue_boucle = 0;
if(pSdlJeu->jeu.avancement == 0)
{
/* Si l'utilisateur a appuyé sur une touche*/
if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 403)&&(event.button.x < 897))
{
if((event.button.y > 242)&&(event.button.y < 317))
{
pSdlJeu->jeu.avancement = 2;
rafraichissement = 1;
}
else if((event.button.x > 403)&&(event.button.x < 897))
{
if((event.button.y > 349)&&(event.button.y < 422))
{
pSdlJeu->jeu.avancement = 10;
rafraichissement = 1;
}
}
}
}
}
}
else if (pSdlJeu->jeu.avancement ==10)
{
/* S'occupper de rentrer les noms des joueurs...
//! Vérifier que minimum deux cases sont remplies*/
if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 1)&&(event.button.x < 1300))
{
if((event.button.y > 1)&&(event.button.y < 688))
{
pSdlJeu->jeu.avancement = 11;
rafraichissement = 1;
}
}
}
}
}
else if (pSdlJeu->jeu.avancement ==11)
{
/* S'occupper de rentrer les noms des joueurs...
//! Vérifier que minimum deux cases sont remplies*/
if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 1)&&(event.button.x < 1300))
{
if((event.button.y > 1)&&(event.button.y < 688))
{
pSdlJeu->jeu.avancement = 0;
rafraichissement = 1;
}
}
}
}
}
else if (pSdlJeu->jeu.avancement ==12)
{
/* S'occupper de rentrer les noms des joueurs...
//! Vérifier que minimum deux cases sont remplies*/
if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 1)&&(event.button.x < 1300))
{
if((event.button.y > 1)&&(event.button.y < 688))
{
pSdlJeu->jeu.avancement = 13;
rafraichissement = 1;
}
}
}
}
}
else if (pSdlJeu->jeu.avancement ==13)
{
/* S'occupper de rentrer les noms des joueurs...
//! Vérifier que minimum deux cases sont remplies*/
if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 1)&&(event.button.x < 1300))
{
if((event.button.y > 1)&&(event.button.y < 688))
{
pSdlJeu->jeu.avancement = 14;
rafraichissement = 1;
}
}
}
}
}
else if (pSdlJeu->jeu.avancement ==14)
{
/* S'occupper de rentrer les noms des joueurs...
//! Vérifier que minimum deux cases sont remplies*/
if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 1)&&(event.button.x < 1300))
{
if((event.button.y > 1)&&(event.button.y < 688))
{
pSdlJeu->jeu.avancement = 15;
rafraichissement = 1;
}
}
}
}
}
else if (pSdlJeu->jeu.avancement ==15)
{
/* S'occupper de rentrer les noms des joueurs...
//! Vérifier que minimum deux cases sont remplies*/
if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 1)&&(event.button.x < 1300))
{
if((event.button.y > 1)&&(event.button.y < 688))
{
pSdlJeu->jeu.avancement = 0;
rafraichissement = 1;
}
}
}
}
}
else if (pSdlJeu->jeu.avancement ==2)
{
/* S'occupper de rentrer les noms des joueurs...
//! Vérifier que minimum deux cases sont remplies*/
if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 854)&&(event.button.x < 1272))
{
if((event.button.y > 280)&&(event.button.y < 437))
{
pSdlJeu->jeu.avancement = 3;
rafraichissement = 1;
}
}
}
}
}
else if (pSdlJeu->jeu.avancement ==3)
{
if(((pSdlJeu->jeu.pi->x_dep4==405) && (pSdlJeu->jeu.pi->y_dep4==90))||((pSdlJeu->jeu.pi->x_dep2==405) &&(pSdlJeu->jeu.pi->y_dep2==90))||((pSdlJeu->jeu.pi->x_dep1==405) &&(pSdlJeu->jeu.pi->y_dep1==90))||((pSdlJeu->jeu.pi->x_dep3==405) &&(pSdlJeu->jeu.pi->y_dep3==90))||
(((pSdlJeu->jeu.pi->x_dep4==810) && (pSdlJeu->jeu.pi->y_dep4==90))||((pSdlJeu->jeu.pi->x_dep2==810) &&(pSdlJeu->jeu.pi->y_dep2==90))||((pSdlJeu->jeu.pi->x_dep1==810) &&(pSdlJeu->jeu.pi->y_dep1==90))||((pSdlJeu->jeu.pi->x_dep3==810) &&(pSdlJeu->jeu.pi->y_dep3==90)))||
(((pSdlJeu->jeu.pi->x_dep4==1100) && (pSdlJeu->jeu.pi->y_dep4==435))||((pSdlJeu->jeu.pi->x_dep2==1100) &&(pSdlJeu->jeu.pi->y_dep2==435))||((pSdlJeu->jeu.pi->x_dep1==1100) &&(pSdlJeu->jeu.pi->y_dep1==435))||((pSdlJeu->jeu.pi->x_dep3==1100) &&(pSdlJeu->jeu.pi->y_dep3==435)))||
(((pSdlJeu->jeu.pi->x_dep4==895) && (pSdlJeu->jeu.pi->y_dep4==600))||((pSdlJeu->jeu.pi->x_dep2==895) &&(pSdlJeu->jeu.pi->y_dep2==600))||((pSdlJeu->jeu.pi->x_dep1==895) &&(pSdlJeu->jeu.pi->y_dep1==600))||((pSdlJeu->jeu.pi->x_dep3==895) &&(pSdlJeu->jeu.pi->y_dep3==600)))||
(((pSdlJeu->jeu.pi->x_dep4==200) && (pSdlJeu->jeu.pi->y_dep4==435))||((pSdlJeu->jeu.pi->x_dep2==200) &&(pSdlJeu->jeu.pi->y_dep2==435))||((pSdlJeu->jeu.pi->x_dep1==200) &&(pSdlJeu->jeu.pi->y_dep1==435))||((pSdlJeu->jeu.pi->x_dep3==200) &&(pSdlJeu->jeu.pi->y_dep3==435)))||
(((pSdlJeu->jeu.pi->x_dep4==200) && (pSdlJeu->jeu.pi->y_dep4==300))||((pSdlJeu->jeu.pi->x_dep2==200) &&(pSdlJeu->jeu.pi->y_dep2==300))))
{
if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 295)&&(event.button.x < 523))
{
if((event.button.y > 147)&&(event.button.y < 325))
{
pSdlJeu->jeu.avancement = 9;
jeTirage_Carte(&pSdlJeu->jeu);
rafraichissement = 1;
}
}
}
}
}
else if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 306)&&(event.button.x < 382))
{
if((event.button.y > 465)&&(event.button.y < 526))
{
pSdlJeu->jeu.avancement = 4;
jeRecup_Des(&pSdlJeu->jeu);
rafraichissement = 1;
}
}
}
}
}
else if (pSdlJeu->jeu.avancement ==4)
{
if ( event.type == SDL_KEYDOWN )
{
switch ( event.key.keysym.sym )
{
case SDLK_a:
pSdlJeu->jeu.pi->numcase=numcase3;
jeDeplacement_Pion3(&pSdlJeu->jeu);
pSdlJeu->jeu.avancement = 5;
rafraichissement = 1;
numcase3=numcase3+pSdlJeu->jeu.d;
break;
case SDLK_z:
pSdlJeu->jeu.pi->numcase=numcase2;
jeDeplacement_Pion2(&pSdlJeu->jeu);
pSdlJeu->jeu.avancement = 6;
rafraichissement = 1;
numcase2=numcase2+pSdlJeu->jeu.d;
break;
case SDLK_e:
pSdlJeu->jeu.pi->numcase=numcase4;
jeDeplacement_Pion4(&pSdlJeu->jeu);
pSdlJeu->jeu.avancement = 7;
rafraichissement = 1;
numcase4=numcase4+pSdlJeu->jeu.d;
break;
case SDLK_r:
pSdlJeu->jeu.pi->numcase=numcase1;
jeDeplacement_Pion1(&pSdlJeu->jeu);
pSdlJeu->jeu.avancement = 8;
rafraichissement = 1;
numcase1=numcase1+pSdlJeu->jeu.d;
break;
default: break;
}
}
}
else if (pSdlJeu->jeu.avancement == 9)
{
if ( event.type == SDL_MOUSEBUTTONDOWN )
{
if(event.button.button == SDL_BUTTON_LEFT)
{
if((event.button.x > 771)&&(event.button.x < 999))
{
if((event.button.y > 351)&&(event.button.y < 728))
{
pSdlJeu->jeu.avancement = 3;
rafraichissement = 1;
}
}
}
}
}
}
if (rafraichissement==1)
{
/* on affiche le jeu sur le buffer caché */
sdljeuAff(pSdlJeu);
/* on permute les deux buffers (cette fonction ne doit se faire qu'une seule fois dans a boucle) */
SDL_Flip( pSdlJeu->ecran );
}
}
}
| 1001-questions | trunk/src/SDL.c | C | gpl2 | 25,899 |
/**
@brief 1001-Questions <br>Permet de créer les cartes de jeu
@author Gaudillat Flavien
@file jeu.h
@version 1.0
@date 2013/12/10
*/
#ifndef JEU_H
#define JEU_H
#include "CASE.h"
#include "CARTE.h"
#include "DE.h"
#include "PION.h"
/**
\struct Jeu
@brief Module du jeu
*/
typedef struct{
DE *de;
TABCASE ta;
CASE *ca;
PION *pi;
JEUCARTES tabcarte;
int nbjoueur;
int avancement;
int d;
int respi;
int resqu;
int reponse;
} JEU;
/**
@brief Initialisation du jeu
@param [in,out] je
@return none
*/
void jeInit_Jeu(JEU* je);
/**
@brief permet de récupérer la valeur des dés
@param [in,out] je
@return none
*/
void jeRecup_Des(JEU* je);
/**
@brief permet le changement de position du pion 1
@param [in,out] je
@return none
*/
void jeDeplacement_Pion1(JEU* je);
/**
@brief permet le changement de position du pion 2
@param [in,out] je
@return none
*/
void jeDeplacement_Pion2(JEU* je);
/**
@brief permet le changement de position du pion 3
@param [in,out] je
@return none
*/
void jeDeplacement_Pion3(JEU* je);
/**
@brief permet le changement de position du pion 4
@param [in,out] je
@return none
*/
void jeDeplacement_Pion4(JEU* je);
/**
@brief permet de demander au joueur si la reponse est juste
@param [in,out] je
@return none
*/
void jeReponse_question(JEU* je);
/**
@brief Permet de mettre à jour les scores des joueurs
@param [in,out] pi
@return none
*/
void jeActualise_Note(JEU* je);
/**
@brief tirage d'une carte et execution du jeu
@param [in,out] car
@return none
*/
void jeTirage_Carte(JEU* je);
/**
@brief Libere l'espace alloué pour la struct JEU
@param [in,out] je
@return none
*/
void jeLibere_Jeu(JEU* je);
#endif
| 1001-questions | trunk/src/JEU.h | C | gpl2 | 1,691 |
#include <malloc.h>
#include <time.h>
#include "SDL.h"
#include "JEU.h"
int main ()
{
SDLJEU sj;
/*TABCASE ca;*/
srand(time(NULL));
sdljeuInit(&sj);
sdljeuBoucle( &sj );
/*ca = caCreer_Case();
printf("%f\n",ca[1].x);*/
return 0;
}
| 1001-questions | trunk/src/main.c | C | gpl2 | 263 |
/**
@brief 1001-Questions <br>Permet de créer les cartes de jeu
@author Gaudillat Flavien
@file PION.h
@version 1.0
@date 2013/12/10
*/
#ifndef PION_H
#define PION_H
#include "JOUEUR.h"
/**
\struct PION
@brief Module des pions de jeu
*/
typedef struct{
char nom[64];
JOUEUR* jo;
float x_dep1;
float y_dep1;
float x_dep2;
float y_dep2;
float x_dep3;
float y_dep3;
float x_dep4;
float y_dep4;
int numcase;
} PION;
/**
@brief Initialisation des pions de jeu
@param [in,out] none
@return pion
*/
PION* piCreer_Pion();
/**
@brief Libere l'espace alloué pour la struct PION
@param [in,out] pi
@return none
*/
void piLibere_Pion(PION *pi);
/**
@brief Test de regression pour le Pion
@param [in,out] none
@return none
*/
void piTest_Pion();
#endif
| 1001-questions | trunk/src/PION.h | C | gpl2 | 794 |
/**
@brief 1001-Questions <br>Permet de créer les cartes de jeu
@author Gaudillat Flavien
@file JOUEUR.h
@version 1.0
@date 2013/12/10
*/
#ifndef JOUEUR_H
#define JOUEUR_H
/**
\struct JOUEUR
@brief Module des pions de jeu
*/
typedef struct{
char nom[64];
unsigned int point;
} JOUEUR;
typedef JOUEUR* TABJOUEUR;
/**
@brief Procédure servant à demander combien de joueur veulent jouer
@param [in,out] none
@return nbjoueur
*/
int joNombre_Joueur();
/**
@brief Initialisation des pions de jeu
@param [in,out] none
@return joueur
*/
TABJOUEUR joCreer_Joueur();
/**
@brief Procédure servant à entrer le nom d'un joueur
@param [in,out] jo
@return none
*/
void joRentrer_Nom(TABJOUEUR * jo, int nbjoueur);
/**
@brief Libere l'espace alloué pour la struct PION
@param [in,out] jo
@return none
*/
void joLibere_Joueur(TABJOUEUR *jo, int nbjoueur);
#endif
| 1001-questions | trunk/src/JOUEUR.h | C | gpl2 | 869 |
/**
@brief 1001-Questions <br>Permet de créer les cartes de jeu
@author Gaudillat Flavien
@file case.h
@version 1.0
@date 2013/12/10
*/
#ifndef CASE_H
#define CASE_H
/**
\struct CASE
@brief Module des cases du jeu
*/
typedef struct{
int num;
char type[32];
float x;
float y;
}CASE;
typedef CASE* TABCASE;
/*typedef enum {ca1=0, ca2, ca3, ca4, ca5, ca6, ca7, ca8, ca9, ca10,
ca11, ca12, ca13, ca14, ca15, ca16, ca17, ca18, ca19, ca20,
ca21, ca22, ca23, ca24, ca25, ca26, ca27, ca28, ca29, ca30,
ca31, ca32, ca33, ca34, ca35, ca36, ca37, ca38, ca39, ca40,
ca41, ca42, ca43, ca44, ca45, ca46, ca47, ca48, ca49, ca50,
ca51, ca52, ca53, ca54, ca55, ca56, ca57, ca58, ca59}NUMCASE;*/
/**
@brief Initialisation d'une case de jeu
@param [in,out] none
@return case
*/
TABCASE caCreer_Case();
/**
@brief Libération de l'espace alloué
@param [in,out] ca
@return none
*/
void caLibere_Case(TABCASE* ca);
/**
@brief Test de regression pour une case
@param [in,out] none
@return none
*/
void caTest_Case();
#endif
| 1001-questions | trunk/src/CASE.h | C | gpl2 | 1,084 |
#include<SDL/SDL.h>
#include<SDL/SDL_image.h>
#include <SDL/SDL_ttf.h>
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
#include<time.h>
#include "CASE.h"
#include "CARTE.h"
#include "DE.h"
#include "PION.h"
#include "JEU.h"
/**
@struct SDLJEU
@brief contient les informations nécessaires pour le déroulement du jeu SDL
*/
typedef struct {
/** Jeu utilisé */
JEU jeu;
/** Surface utilisée pour afficher le Menu */
SDL_Surface* surface_Menu;
/** Surface utilisée pour afficher la saisie des joueurs dans le menu */
SDL_Surface* surface_MenuJoueur;
/** Surface utilisée pour afficher l'image du plateau */
SDL_Surface* surface_PlateauFinal;
/** Surface utilisée pour afficher le logo du jeu */
SDL_Surface* surface_LogoFacopoly;
/** Surfaces utilisées pour afficher les 12 cartes MAIL */
SDL_Surface* surface_Mcar1;
SDL_Surface* surface_Mcar2;
SDL_Surface* surface_Mcar3;
SDL_Surface* surface_Mcar4;
SDL_Surface* surface_Mcar5;
SDL_Surface* surface_Mcar6;
SDL_Surface* surface_Mcar7;
SDL_Surface* surface_Mcar8;
/** Surfaces utilisées pour afficher les 12 cartes REFERENT PEFAGOGIQUE */
SDL_Surface* surface_RPcar1;
SDL_Surface* surface_RPcar2;
SDL_Surface* surface_RPcar3;
SDL_Surface* surface_RPcar4;
SDL_Surface* surface_RPcar5;
/** Surfaces utilisées pour les pions */
SDL_Surface* pion1;
/** Surface utilisée pour l'écran */
SDL_Surface* ecran;
/** Surface utilisée pour les règles */
SDL_Surface* surface_regle1;
SDL_Surface* surface_regle2;
/** Surface utilisée pour les pions */
SDL_Surface* surface_1;
SDL_Surface* surface_2;
SDL_Surface* surface_3;
SDL_Surface* surface_4;
/** Surface utilisée pour les points */
SDL_Surface* score1;
SDL_Surface* score2;
SDL_Surface* score3;
SDL_Surface* score4;
/** Surface utilisée pour les des */
SDL_Surface* de;
} SDLJEU;
/** @brief affiche_plateau procedure SDL qui permet l'affichage du tableau avec l'image de fond
@param ecran une surface SDL en mode video
@param plateau le tableau d'elements initialise
*/
int affiche_plateau (SDL_Surface *ecran);
/**
@brief initialise le jeu en sdl
@param [in,out] pSdlJeu
*/
void sdljeuInit(SDLJEU *pSdlJeu);
/** @brief affiche_plateau procedure SDL qui permet l'affichage d'une carte
@param [in,out] pSdlJeu
*/
void sdlAff_Carte(SDLJEU *pSdlJeu);
/** @brief affiche_plateau procedure SDL qui permet l'affichage du pion 1
@param [in,out] pSdlJeu
*/
void sdlAff_1(SDLJEU *pSdlJeu);
/** @brief affiche_plateau procedure SDL qui permet l'affichage du pion 2
@param [in,out] pSdlJeu
*/
void sdlAff_2(SDLJEU *pSdlJeu);
/** @brief affiche_plateau procedure SDL qui permet l'affichage du pion 3
@param [in,out] pSdlJeu
*/
void sdlAff_3(SDLJEU *pSdlJeu);
/** @brief affiche_plateau procedure SDL qui permet l'affichage du pion 4
@param [in,out] pSdlJeu
*/
void sdlAff_4(SDLJEU *pSdlJeu);
/** @brief affiche_plateau procedure SDL qui permet l'affichage du score
@param [in,out] pSdlJeu
*/
void sdlAff_Score(SDLJEU *pSdlJeu);
/** @brief affiche_plateau procedure SDL qui permet l'affichage le chiffre donner par les dé
@param [in,out] pSdlJeu
*/
void sdlAff_De(SDLJEU *pSdlJeu);
/**
@brief affiche le jeu en sdl
@param [in,out] pSdlJeu
*/
void sdljeuAff(SDLJEU *pSdlJeu);
/**
@brief boucle qui traite tous les cas d'action du jeu
@param [in,out] pSdlJeu
*/
void sdljeuBoucle(SDLJEU * pSdlJeu);
int SDLinterface(SDLJEU *pSdlJeu);
| 1001-questions | trunk/src/SDL.h | C | gpl2 | 3,599 |
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include "DE.h"
DE* deCreer_De()
{
DE* d=(DE*) malloc(sizeof(DE));
d->de1=0;
d->de2=0;
return d;
}
void deTirage_Alea(DE* d)
{
d->de1 = rand() % 6 + 1;
d->de2 = rand() % 6 + 1;
}
void deLibere_De(DE* d)
{
free(d);
}
void deTest_de()
{
DE *d;
int alea1;
int alea2;
d = deCreer_De();
srand(time(NULL));
alea1 = rand() % 6 + 1 ;
alea2 = rand() % 6 + 1 ;
printf("Tests du module de : \n\n") ;
/* Début du test de deCreer_De*/
printf("Test de deCreer_De ... \n") ;
assert(d->de1== 0);
assert(d->de2== 0);
/* Début du test de deTirage_Alea*/
deTirage_Alea(d);
printf("Test de deTirage_Alea ... \n");
assert(d->de1== alea1);
assert(d->de2== alea2);
free(d);
printf("Tests du module DE terminé \n\n") ;
}
| 1001-questions | trunk/src/DE.c | C | gpl2 | 910 |
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "CASE.h"
#include <malloc.h>
TABCASE caCreer_Case()
{
TABCASE ta=(CASE*) malloc(41*sizeof(CASE));
ta[1].num = 1;
strcpy(ta[1].type , "départ");
ta[1].x = 66;
ta[1].y = 1137;
ta[2].num = 2;
strcpy(ta[2].type , "vide");
ta[2].x = 66;
ta[2].y = 1059;
ta[3].num = 3;
strcpy(ta[3].type , "vide");
ta[3].x = 66;
ta[3].y = 960;
ta[4].num = 4;
strcpy(ta[4].type , "question");
ta[4].x = 66;
ta[4].y = 873;
ta[5].num = 5;
strcpy(ta[5].type , "vide");
ta[5].x = 66;
ta[5].y = 780;
ta[6].num = 6;
strcpy(ta[6].type , "pieges");
ta[6].x = 66;
ta[6].y = 680;
ta[7].num = 7;
strcpy(ta[7].type, "vide");
ta[7].x = 66;
ta[7].y = 590;
ta[8].num = 8;
strcpy(ta[8].type , "pieges");
ta[8].x = 66;
ta[8].y = 510;
ta[9].num = 9;
strcpy(ta[9].type , "vide");
ta[9].x = 66;
ta[9].y = 420;
ta[10].num = 10;
strcpy(ta[10].type , "question");
ta[10].x = 66;
ta[10].y = 320;
ta[11].num = 11;
strcpy(ta[11].type , "vide");
ta[11].x = 66;
ta[11].y = 234;
ta[12].num = 12;
strcpy(ta[12].type , "vide");
ta[12].x = 159;
ta[12].y = 234;
ta[13].num = 13;
strcpy(ta[13].type , "question");
ta[13].x = 246;
ta[13].y = 234;
ta[14].num = 14;
strcpy(ta[14].type , "vide");
ta[14].x = 333;
ta[14].y = 234;
ta[15].num = 15;
strcpy(ta[15].type , "pieges");
ta[15].x = 411;
ta[15].y = 234;
ta[16].num = 16;
strcpy(ta[16].type , "vide");
ta[16].x = 507;
ta[16].y = 234;
ta[17].num = 17;
strcpy(ta[17].type , "vide");
ta[17].x = 591;
ta[17].y = 234;
ta[18].num = 18;
strcpy(ta[18].type , "question");
ta[18].x = 669;
ta[18].y = 234;
ta[19].num = 19;
strcpy(ta[19].type , "vide");
ta[19].x = 765;
ta[19].y = 234;
ta[20].num = 20;
strcpy(ta[20].type , "tremplin");
ta[20].x = 765;
ta[20].y = 327;
ta[21].num = 21;
strcpy(ta[21].type , "vide");
ta[21].x = 765;
ta[21].y = 417;
ta[22].num = 22;
strcpy(ta[22].type , "vide");
ta[22].x = 681;
ta[22].y = 417;
ta[23].num = 23;
strcpy(ta[23].type , "vide");
ta[23].x = 582;
ta[23].y = 417;
ta[24].num = 24;
strcpy(ta[24].type , "question");
ta[24].x = 504;
ta[24].y = 417;
ta[25].num = 25;
strcpy(ta[25].type , "vide");
ta[25].x = 414;
ta[25].y = 417;
ta[26].num = 26;
strcpy(ta[26].type , "pieges");
ta[26].x = 330;
ta[26].y = 417;
ta[27].num = 27;
strcpy(ta[27].type , "vide");
ta[27].x = 249;
ta[27].y = 417;
ta[28].num = 28;
strcpy(ta[28].type , "tempete");
ta[28].x = 249;
ta[28].y = 510;
ta[29].num = 29;
strcpy(ta[29].type , "vide");
ta[29].x = 249;
ta[29].y = 600;
ta[30].num = 30;
strcpy(ta[30].type , "vide");
ta[30].x = 336;
ta[30].y = 600;
ta[31].num = 31;
strcpy(ta[31].type , "question");
ta[31].x = 411;
ta[31].y = 600;
ta[32].num = 32;
strcpy(ta[32].type , "vide");
ta[32].x = 501;
ta[32].y = 600;
ta[33].num = 33;
strcpy(ta[33].type , "piege");
ta[33].x = 488;
ta[33].y = 600;
ta[34].num = 34;
strcpy(ta[34].type , "vide");
ta[34].x = 678;
ta[34].y = 600;
ta[35].num = 35;
strcpy(ta[35].type , "tremplin");
ta[35].x = 765;
ta[35].y = 600;
ta[36].num = 36;
strcpy(ta[36].type , "vide");
ta[36].x = 765;
ta[36].y = 680;
ta[37].num = 37;
strcpy(ta[37].type , "vide");
ta[37].x = 765;
ta[37].y = 793;
ta[38].num = 38;
strcpy(ta[38].type , "quesition");
ta[38].x = 672;
ta[38].y = 793;
ta[39].num = 39;
strcpy(ta[39].type , "pieges");
ta[39].x = 585;
ta[39].y = 793;
ta[40].num = 40;
strcpy(ta[40].type , "vide");
ta[40].x = 507;
ta[40].y = 793;
ta[41].num = 41;
strcpy(ta[41].type , "vide");
ta[41].x = 414;
ta[41].y = 793;
ta[42].num = 42;
strcpy(ta[42].type , "vide");
ta[42].x = 333;
ta[42].y = 793;
ta[43].num = 43;
strcpy(ta[43].type , "vide");
ta[43].x = 243;
ta[43].y = 793;
ta[44].num = 44;
strcpy(ta[44].type , "tremplin");
ta[44].x = 243;
ta[44].y = 882;
ta[45].num = 45;
strcpy(ta[45].type , "tempete");
ta[45].x = 243;
ta[45].y = 969;
ta[46].num = 46;
strcpy(ta[46].type , "tremplin");
ta[46].x = 333;
ta[46].y = 969;
ta[47].num = 47;
strcpy(ta[47].type , "vide");
ta[47].x = 414;
ta[47].y = 969;
ta[48].num = 48;
strcpy(ta[48].type , "question");
ta[48].x = 504;
ta[48].y = 969;
ta[49].num = 49;
strcpy(ta[49].type , "vide");
ta[49].x = 590;
ta[49].y = 969;
ta[50].num = 50;
strcpy(ta[50].type , "tempete");
ta[50].x = 675;
ta[50].y = 969;
ta[51].num = 51;
strcpy(ta[51].type , "vide");
ta[51].x = 775;
ta[51].y = 969;
ta[52].num = 52;
strcpy(ta[52].type , "pieges");
ta[52].x = 775;
ta[52].y = 1059;
ta[53].num = 53;
strcpy(ta[53].type , "vide");
ta[53].x = 775;
ta[53].y = 1140;
ta[54].num = 54;
strcpy(ta[54].type , "vide");
ta[54].x = 681;
ta[54].y = 1140;
ta[55].num = 55;
strcpy(ta[55].type , "question");
ta[55].x = 582;
ta[55].y = 1140;
ta[56].num = 56;
strcpy(ta[56].type , "vide");
ta[56].x = 501;
ta[56].y = 1140;
ta[57].num = 57;
strcpy(ta[57].type , "tempete");
ta[57].x = 417;
ta[57].y = 1140;
ta[58].num = 58;
strcpy(ta[58].type , "vide");
ta[58].x = 324;
ta[58].y = 1140;
ta[59].num = 59;
strcpy(ta[59].type , "arrive");
ta[59].x = 234;
ta[59].y = 1140;
return ta;
}
void caLibere_case(TABCASE* ca)
{
int i;
for (i=1; i<=40; i++)
{
free (ca[i]);
}
}
void caTest_Case()
{
TABCASE ca;
int i;
ca = caCreer_Case();
printf("Tests du module CASE : \n\n") ;
/* Début du test de caCreer_Case*/
printf("Test de caCreer_Case ... \n") ;
for(i=1; i<=59; i++)
{
assert(ca[i].num== i);
assert(!(strcmp(ca[i].type, "")));
assert(ca[i].x != 0);
assert(ca[i].y != 0);
}
assert(i==59);
caLibere_case(&ca);
printf("Tests du module CASE terminé \n\n") ;
}
| 1001-questions | trunk/src/CASE.c | C | gpl2 | 6,471 |
#!/usr/bin/env python
"""
Network Monitoring System Server Mock
"""
import json, socket
hash_number = 1;
def register(params):
answer = { 'command':'register' }
global hash_number
services=''
client_hash = params['hash']
client_port = params['port']
client_service_list = params['service_list']
if client_hash == '':
answer['status'] = 1 # 1 - means ok
answer['hash'] = hash_number
hash_number += 1
elif client_hash == -1:
answer['status'] = 2 # 2 - force new hash
answer['hash'] = ''
else:
answer['status'] = 0 # 0 - means hash reuse
answer['hash'] = client_hash
for i in client_service_list:
services = services + i
print (str(client_hash) + ';' + str(client_port) + ';' + services)
return answer;
# End of function
def unsupported():
return { 'command' : 'unknown', 'status' : -1 }
# End of funciton
options = {}
options['host'] = ''
options['port'] = 5000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((options['host'],options['port']))
server.listen(5)
print 'Network Monitoring Simple Server started'
while 1:
client, address = server.accept()
clientData = client.recv(1024)
question = json.loads(clientData)
if question['command'] == 'register':
response = register(question['params'])
else:
print "Unsupported command"
response = unsupported()
response = json.dumps(response)
client.send(response)
exit(0)
| 11z-zpr-netspy | trunk/client/tests/.svn/text-base/spynet-server-register-mock.py.svn-base | Python | gpl3 | 1,403 |
#!/usr/bin/env python
"""
Network Monitoring System Server Mock
"""
import json, socket
hash_number = 1;
def register(params):
answer = { 'command':'register' }
global hash_number
services=''
client_hash = params['hash']
client_port = params['port']
client_service_list = params['service_list']
if client_hash == '':
answer['status'] = 1 # 1 - means ok
answer['hash'] = hash_number
hash_number += 1
elif client_hash == -1:
answer['status'] = 2 # 2 - force new hash
answer['hash'] = ''
else:
answer['status'] = 0 # 0 - means hash reuse
answer['hash'] = client_hash
for i in client_service_list:
services = services + i
print (str(client_hash) + ';' + str(client_port) + ';' + services)
return answer;
# End of function
def unsupported():
return { 'command' : 'unknown', 'status' : -1 }
# End of funciton
options = {}
options['host'] = ''
options['port'] = 5000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((options['host'],options['port']))
server.listen(5)
print 'Network Monitoring Simple Server started'
while 1:
client, address = server.accept()
clientData = client.recv(1024)
question = json.loads(clientData)
if question['command'] == 'register':
response = register(question['params'])
else:
print "Unsupported command"
response = unsupported()
response = json.dumps(response)
client.send(response)
exit(0)
| 11z-zpr-netspy | trunk/client/tests/spynet-server-register-mock.py | Python | gpl3 | 1,403 |
#!/usr/bin/env python
"""
NetSpy Client
by Marcin Ciechowicz for ZPR
v0.01
"""
import socket
import json
from subprocess import call
import logging
import argparse
import os.path
appName = 'NetSpyClient'
scriptDir = 'scripts'
logger = logging.getLogger(appName)
def initLogger():
formatter = logging.Formatter('%(asctime)s %(levelname)s::%(message)s')
hdlrFile = logging.FileHandler(appName + '.log')
hdlrFile.setFormatter(formatter)
hdlrStd = logging.StreamHandler()
hdlrStd.setFormatter(formatter)
logger.addHandler(hdlrFile)
logger.addHandler(hdlrStd)
logger.setLevel(logging.DEBUG)
class Service:
name = ''
testerPath = ''
def __init__(self, name, testerPath):
"""Creates service"""
self.name = name
self.testerPath = testerPath
def getName(self):
return self.name
def getCheckerPath(self):
return self.checkerPath
def executeCheck(self):
return call(testerPath,'1')
class Config:
options = {}
def __init__(self, fileName = "netspy.conf"):
"""Initialize config from file """
self.options = {'port' : '', 'server_port' : '', 'server_ip': '', 'service_list': [] }
self.fileName = fileName
self.loadFromFile(self.fileName)
def loadFromFile(self,fileName):
try:
logger.info("Reading config file: " + fileName)
configFile = file(fileName,'r')
line = configFile.readline()
active_options = ('port','server_port','server_ip')
while line != '' :
tokens = line.strip().split(' ')
if tokens[0] == 'service':
if (tokens[1] == 'alive'):
logger.warning("Service " + tokens[1] + " is already definied, please use different name")
elif (os.path.isfile(scriptDir+'/'+tokens[2])):
self.options['service_list'].append(Service(tokens[1],tokens[2]))
logger.debug("New service added: " + tokens[1])
else:
logger.warning("Service " + tokens[1] +" error: Can't find script : " + scriptDir + '/' + tokens[2])
logger.warning("Service " + tokens[1] +" creation failed")
elif tokens[0] in active_options:
self.options[tokens[0]]=tokens[1]
logger.debug(tokens[0] + " set to " + tokens[1])
else:
logger.warning("Unkown option " + tokens[0])
line = configFile.readline()
configFile.close()
except IOError:
logger.error( "Can't read " + fileName)
exit()
def getPort(self):
return self.options['port']
def getServerPort(self):
return self.options['server_port']
def getServerIp(self):
return self.options['server_ip']
def getServiceList(self):
return self.options['service_list']
class ClientApp:
config = ''
def getHash(self):
hashValue=''
try:
hashFile=file(".netspy.hash","r")
hashValue = hashFile.readline()
except IOError:
logger.warining( "No hash found")
finally:
return hashValue
def setHash(self,hashValue):
""" Function doc """
if (hashValue!=''):
try:
hashFile=file(".netspy.hash","w")
hashFile.write(hashValue)
except IOError:
logger.error( "Can't store hash value")
exit(0)
def setConfig(self, config):
self.config = config
def __init__(self,config=None):
if config!=None:
self.setConfig(config)
def hashCheck(self,hashValue):
return True
def init(self):
logger.info('Client - running ')
def registerAtServer(self):
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((self.config.getServerIp(), int(self.config.getServerPort()) ))
except IOError:
logger.error("Can't register at monitoring server - connection problem")
return False
service_list = [];
for i in self.config.getServiceList():
service_list.append(i.getName())
service_list.append('alive')
message = { 'command' : 'register', 'payload': {'hash' : self.getHash(), 'port' : self.config.getPort(), 'service_list' : service_list }}
messageToSend = json.dumps(message)
server.send(messageToSend)
data = server.recv(1024)
server.close()
answer = json.loads(data)
if (answer['command'] != 'register'):
logger.error("Bad command type - expected 'register'")
return False
if (answer['payload']['status'] == 0):
logger.info("Reusing old hash")
return True
elif (answer['payload']['status'] == 1):
logger.info("Saving new hash: " + str(answer['payload']['hash']))
hashValue = answer['payload']['hash']
self.setHash(str(hashValue))
return True
elif (answer['payload']['status'] == 2):
clear = file('.netspy.hash','w')
clear.write('')
return False
else:
return False
def performServiceCheck(self,message):
try:
question = json.loads(message)
if question['command'] != 'check_status':
logger.error("Unknown command '" + question['command'] + "'received from server")
logger.error("No check performed")
return
else:
logger.info("Performing check")
resultList = []
alive = { 'alive' : 0 }
resultList.append(alive)
for service in self.config.getServiceList():
tmp = service.executeCheck()
result = {service.getName() : tmp }
resultList.append(result)
answer = {'command' : 'check_status', 'payload' : {'check_result' : resultList }}
return json.dumps(answer);
except ValueError:
logger.error("Unsupported command format")
logger.error("No check performed")
def run(self):
logger.info("Client - registering at monitoring server")
i=0
while (i<3 and not self.registerAtServer()):
i=i+1
if (i==3):
logger.error("Connect to monitoring server failed - can't connect to specified host")
logger.error("Please check your config file")
return
logger.info("Client - register succesful")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.bind(('',int(self.config.getPort())))
client.listen(5)
logger.info('Client - waiting for commands from server')
while 1:
request, address = client.accept()
message = request.recv(1024)
answer = self.performServiceCheck(message)
request.send(answer)
request.close()
def parseArgs():
parser = argparse.ArgumentParser(prog=appName, usage='%(prog)s [options]')
parser.add_argument('--verbose','-v', action='store_false', help='verbose mode')
parser.add_argument('--config','-c', action='store', help='config filename')
args = parser.parse_args()
if args.verbose == True:
logger.setLevel(logging.ERROR)
if args.config != None:
return Config(args.config)
else:
return Config()
#---------- main --------------------------#
initLogger()
client = ClientApp(parseArgs())
client.init()
client.run()
#-----------------------------------------#
| 11z-zpr-netspy | trunk/client/.svn/text-base/netspy-client.py.svn-base | Python | gpl3 | 6,560 |
#!/usr/bin/env python
"""
NetSpy Client
by Marcin Ciechowicz for ZPR
v0.01
"""
import socket
import json
from subprocess import call
import logging
import argparse
import os.path
appName = 'NetSpyClient'
scriptDir = 'scripts'
logger = logging.getLogger(appName)
def initLogger():
formatter = logging.Formatter('%(asctime)s %(levelname)s::%(message)s')
hdlrFile = logging.FileHandler(appName + '.log')
hdlrFile.setFormatter(formatter)
hdlrStd = logging.StreamHandler()
hdlrStd.setFormatter(formatter)
logger.addHandler(hdlrFile)
logger.addHandler(hdlrStd)
logger.setLevel(logging.DEBUG)
class Service:
name = ''
testerPath = ''
def __init__(self, name, testerPath):
"""Creates service"""
self.name = name
self.testerPath = testerPath
def getName(self):
return self.name
def getCheckerPath(self):
return self.checkerPath
def executeCheck(self):
return call(testerPath,'1')
class Config:
options = {}
def __init__(self, fileName = "netspy.conf"):
"""Initialize config from file """
self.options = {'port' : '', 'server_port' : '', 'server_ip': '', 'service_list': [] }
self.fileName = fileName
self.loadFromFile(self.fileName)
def loadFromFile(self,fileName):
try:
logger.info("Reading config file: " + fileName)
configFile = file(fileName,'r')
line = configFile.readline()
active_options = ('port','server_port','server_ip')
while line != '' :
tokens = line.strip().split(' ')
if tokens[0] == 'service':
if (tokens[1] == 'alive'):
logger.warning("Service " + tokens[1] + " is already definied, please use different name")
elif (os.path.isfile(scriptDir+'/'+tokens[2])):
self.options['service_list'].append(Service(tokens[1],tokens[2]))
logger.debug("New service added: " + tokens[1])
else:
logger.warning("Service " + tokens[1] +" error: Can't find script : " + scriptDir + '/' + tokens[2])
logger.warning("Service " + tokens[1] +" creation failed")
elif tokens[0] in active_options:
self.options[tokens[0]]=tokens[1]
logger.debug(tokens[0] + " set to " + tokens[1])
else:
logger.warning("Unkown option " + tokens[0])
line = configFile.readline()
configFile.close()
except IOError:
logger.error( "Can't read " + fileName)
exit()
def getPort(self):
return self.options['port']
def getServerPort(self):
return self.options['server_port']
def getServerIp(self):
return self.options['server_ip']
def getServiceList(self):
return self.options['service_list']
class ClientApp:
config = ''
def getHash(self):
hashValue=''
try:
hashFile=file(".netspy.hash","r")
hashValue = hashFile.readline()
except IOError:
logger.warining( "No hash found")
finally:
return hashValue
def setHash(self,hashValue):
""" Function doc """
if (hashValue!=''):
try:
hashFile=file(".netspy.hash","w")
hashFile.write(hashValue)
except IOError:
logger.error( "Can't store hash value")
exit(0)
def setConfig(self, config):
self.config = config
def __init__(self,config=None):
if config!=None:
self.setConfig(config)
def hashCheck(self,hashValue):
return True
def init(self):
logger.info('Client - running ')
def registerAtServer(self):
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((self.config.getServerIp(), int(self.config.getServerPort()) ))
except IOError:
logger.error("Can't register at monitoring server - connection problem")
return False
service_list = [];
for i in self.config.getServiceList():
service_list.append(i.getName())
service_list.append('alive')
message = { 'command' : 'register', 'payload': {'hash' : self.getHash(), 'port' : self.config.getPort(), 'service_list' : service_list }}
messageToSend = json.dumps(message)
server.send(messageToSend)
data = server.recv(1024)
server.close()
answer = json.loads(data)
if (answer['command'] != 'register'):
logger.error("Bad command type - expected 'register'")
return False
if (answer['payload']['status'] == 0):
logger.info("Reusing old hash")
return True
elif (answer['payload']['status'] == 1):
logger.info("Saving new hash: " + str(answer['payload']['hash']))
hashValue = answer['payload']['hash']
self.setHash(str(hashValue))
return True
elif (answer['payload']['status'] == 2):
clear = file('.netspy.hash','w')
clear.write('')
return False
else:
return False
def performServiceCheck(self,message):
try:
question = json.loads(message)
if question['command'] != 'check_status':
logger.error("Unknown command '" + question['command'] + "'received from server")
logger.error("No check performed")
return
else:
logger.info("Performing check")
resultList = []
alive = { 'alive' : 0 }
resultList.append(alive)
for service in self.config.getServiceList():
tmp = service.executeCheck()
result = {service.getName() : tmp }
resultList.append(result)
answer = {'command' : 'check_status', 'payload' : {'check_result' : resultList }}
return json.dumps(answer);
except ValueError:
logger.error("Unsupported command format")
logger.error("No check performed")
def run(self):
logger.info("Client - registering at monitoring server")
i=0
while (i<3 and not self.registerAtServer()):
i=i+1
if (i==3):
logger.error("Connect to monitoring server failed - can't connect to specified host")
logger.error("Please check your config file")
return
logger.info("Client - register succesful")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.bind(('',int(self.config.getPort())))
client.listen(5)
logger.info('Client - waiting for commands from server')
while 1:
request, address = client.accept()
message = request.recv(1024)
answer = self.performServiceCheck(message)
request.send(answer)
request.close()
def parseArgs():
parser = argparse.ArgumentParser(prog=appName, usage='%(prog)s [options]')
parser.add_argument('--verbose','-v', action='store_false', help='verbose mode')
parser.add_argument('--config','-c', action='store', help='config filename')
args = parser.parse_args()
if args.verbose == True:
logger.setLevel(logging.ERROR)
if args.config != None:
return Config(args.config)
else:
return Config()
#---------- main --------------------------#
initLogger()
client = ClientApp(parseArgs())
client.init()
client.run()
#-----------------------------------------#
| 11z-zpr-netspy | trunk/client/netspy-client.py | Python | gpl3 | 6,560 |
#line 1 "skinMainView.tmpl"
#include "content.h"
#line 2 "skinMainView.tmpl"
#include "constants.h"
#line 3 "skinMainView.tmpl"
namespace my_skin {
#line 5 "skinMainView.tmpl"
struct master :public cppcms::base_view
#line 5 "skinMainView.tmpl"
{
#line 5 "skinMainView.tmpl"
cppcms::base_content &content;
#line 5 "skinMainView.tmpl"
master(std::ostream &_s,cppcms::base_content &_content): cppcms::base_view(_s),content(_content)
#line 5 "skinMainView.tmpl"
{
#line 5 "skinMainView.tmpl"
}
#line 6 "skinMainView.tmpl"
virtual void menu() {
#line 9 "skinMainView.tmpl"
out()<<"\n"
" <div id=\"menu\">\n"
" <ul>\n"
" <li><a href=\"";
#line 9 "skinMainView.tmpl"
out()<<ROOT
#line 10 "skinMainView.tmpl"
out()<<"/overview\">overview</a></li>\n"
" <li><a href=\"";
#line 10 "skinMainView.tmpl"
out()<<ROOT
#line 11 "skinMainView.tmpl"
out()<<"/clients\">clients</a></li>\n"
" <li><a href=\"";
#line 11 "skinMainView.tmpl"
out()<<ROOT
#line 14 "skinMainView.tmpl"
out()<<"/services\">services</a></li>\n"
" </ul>\n"
" </div>\n"
" ";
#line 14 "skinMainView.tmpl"
} // end of template menu
#line 15 "skinMainView.tmpl"
virtual void head() {
#line 18 "skinMainView.tmpl"
out()<<"\n"
" <head>\n"
" <title>11z-zpr-netspy</title>\n"
" ";
#line 18 "skinMainView.tmpl"
css();
#line 19 "skinMainView.tmpl"
out()<<"\n"
" ";
#line 19 "skinMainView.tmpl"
javascript();
#line 21 "skinMainView.tmpl"
out()<<"\n"
" </head>\n"
" ";
#line 21 "skinMainView.tmpl"
} // end of template head
#line 22 "skinMainView.tmpl"
virtual void javascript() {
#line 23 "skinMainView.tmpl"
out()<<"\n"
" <script type=\"text/javascript\" src=\"";
#line 23 "skinMainView.tmpl"
out()<<ROOT;
#line 24 "skinMainView.tmpl"
out()<<"/../script/default.js\"></script>\n"
" ";
#line 24 "skinMainView.tmpl"
} // end of template javascript
#line 25 "skinMainView.tmpl"
virtual void css() {
#line 26 "skinMainView.tmpl"
out()<<"\n"
" <link rel=\"stylesheet\" href=\"";
#line 26 "skinMainView.tmpl"
out()<<ROOT;
#line 27 "skinMainView.tmpl"
out()<<"/../style/default.css\" type=\"text/css\" media=\"all\" />\n"
" ";
#line 27 "skinMainView.tmpl"
} // end of template css
#line 28 "skinMainView.tmpl"
virtual void link_comp(std::string &label,std::string &id) {
#line 29 "skinMainView.tmpl"
out()<<"\n"
" <a href=\"";
#line 29 "skinMainView.tmpl"
out()<<ROOT
#line 29 "skinMainView.tmpl"
out()<<"/comp/";
#line 29 "skinMainView.tmpl"
out()<<id;
#line 29 "skinMainView.tmpl"
out()<<"\">";
#line 29 "skinMainView.tmpl"
out()<<label;
#line 30 "skinMainView.tmpl"
out()<<"</a>\n"
" ";
#line 30 "skinMainView.tmpl"
} // end of template link_comp
#line 31 "skinMainView.tmpl"
}; // end of class master
#line 33 "skinMainView.tmpl"
struct services :public master
#line 33 "skinMainView.tmpl"
{
#line 33 "skinMainView.tmpl"
content::services &content;
#line 33 "skinMainView.tmpl"
services(std::ostream &_s,content::services &_content): master(_s,_content),content(_content)
#line 33 "skinMainView.tmpl"
{
#line 33 "skinMainView.tmpl"
}
#line 34 "skinMainView.tmpl"
virtual void render() {
#line 36 "skinMainView.tmpl"
out()<<" \n"
" <html>\n"
" ";
#line 36 "skinMainView.tmpl"
master::head();
#line 38 "skinMainView.tmpl"
out()<<"\n"
" <body>\n"
" ";
#line 38 "skinMainView.tmpl"
master::menu();
#line 46 "skinMainView.tmpl"
out()<<"\n"
" <table>\n"
" <thead>\n"
" <tr>\n"
" <td>service description</td>\n"
" </tr>\n"
" </thead>\n"
" <tbody>\n"
" ";
#line 46 "skinMainView.tmpl"
for(int i=0; i<content.size; ++i){
#line 48 "skinMainView.tmpl"
out()<<"\n"
" <tr>\n"
" <td><a href=\"";
#line 48 "skinMainView.tmpl"
out()<<ROOT
#line 48 "skinMainView.tmpl"
out()<<"/service/";
#line 48 "skinMainView.tmpl"
out()<<content.id.at(i) ;
#line 48 "skinMainView.tmpl"
out()<<"\">";
#line 48 "skinMainView.tmpl"
out()<<content.description.at(i) ;
#line 50 "skinMainView.tmpl"
out()<<"</a></td>\n"
" </tr>\n"
" ";
#line 50 "skinMainView.tmpl"
}
#line 55 "skinMainView.tmpl"
out()<<"\n"
" </tbody>\n"
" </table>\n"
" </body> \n"
" <html> \n"
" ";
#line 55 "skinMainView.tmpl"
} // end of template render
#line 56 "skinMainView.tmpl"
}; // end of class services
#line 58 "skinMainView.tmpl"
struct overview :public master
#line 58 "skinMainView.tmpl"
{
#line 58 "skinMainView.tmpl"
content::overview &content;
#line 58 "skinMainView.tmpl"
overview(std::ostream &_s,content::overview &_content): master(_s,_content),content(_content)
#line 58 "skinMainView.tmpl"
{
#line 58 "skinMainView.tmpl"
}
#line 59 "skinMainView.tmpl"
virtual void render() {
#line 61 "skinMainView.tmpl"
out()<<" \n"
" <html> \n"
" ";
#line 61 "skinMainView.tmpl"
master::head();
#line 63 "skinMainView.tmpl"
out()<<"\n"
" <body>\n"
" ";
#line 63 "skinMainView.tmpl"
master::menu();
#line 77 "skinMainView.tmpl"
out()<<"\n"
" <table>\n"
" <thead>\n"
" <tr>\n"
" <td>ip</td>\n"
" <td>port</td>\n"
" <td>client remarks</td>\n"
" <td>service</td>\n"
" <td>timestamp</td>\n"
" <td>status</td>\n"
" <td></td>\n"
" </tr>\n"
" </thead>\n"
" <tbody>\n"
" ";
#line 77 "skinMainView.tmpl"
for(int i=0; i<content.size; ++i){
#line 78 "skinMainView.tmpl"
out()<<"\n"
" <tr class=\"";
#line 78 "skinMainView.tmpl"
out()<<content.status.at(i);
#line 79 "skinMainView.tmpl"
out()<<"\">\n"
" <td><a href=\"";
#line 79 "skinMainView.tmpl"
out()<<ROOT
#line 79 "skinMainView.tmpl"
out()<<"/comp/";
#line 79 "skinMainView.tmpl"
out()<<content.comp_id.at(i);
#line 79 "skinMainView.tmpl"
out()<<"\">";
#line 79 "skinMainView.tmpl"
out()<<content.ip.at(i) ;
#line 80 "skinMainView.tmpl"
out()<<"</a></td> \n"
" <td>";
#line 80 "skinMainView.tmpl"
out()<<content.port.at(i) ;
#line 81 "skinMainView.tmpl"
out()<<"</td>\n"
" <td>";
#line 81 "skinMainView.tmpl"
out()<<content.remarks.at(i) ;
#line 82 "skinMainView.tmpl"
out()<<"</td>\n"
" <td><a href=\"";
#line 82 "skinMainView.tmpl"
out()<<ROOT
#line 82 "skinMainView.tmpl"
out()<<"/service/";
#line 82 "skinMainView.tmpl"
out()<<content.service_id.at(i);
#line 82 "skinMainView.tmpl"
out()<<"\">";
#line 82 "skinMainView.tmpl"
out()<<content.service.at(i);
#line 83 "skinMainView.tmpl"
out()<<"</a></td>\n"
" <td>";
#line 83 "skinMainView.tmpl"
out()<<content.timestamp.at(i) ;
#line 84 "skinMainView.tmpl"
out()<<"</td>\n"
" <td>";
#line 84 "skinMainView.tmpl"
out()<<content.status.at(i) ;
#line 85 "skinMainView.tmpl"
out()<<"</td>\n"
" <td><a href=\"";
#line 85 "skinMainView.tmpl"
out()<<ROOT
#line 85 "skinMainView.tmpl"
out()<<"/service/";
#line 85 "skinMainView.tmpl"
out()<<content.service_id.at(i);
#line 85 "skinMainView.tmpl"
out()<<"/comp/";
#line 85 "skinMainView.tmpl"
out()<<content.comp_id.at(i);
#line 87 "skinMainView.tmpl"
out()<<"\">history</a></td>\n"
" </tr>\n"
" ";
#line 87 "skinMainView.tmpl"
}
#line 92 "skinMainView.tmpl"
out()<<"\n"
" </tbody>\n"
" </table>\n"
" </body> \n"
" <html> \n"
" ";
#line 92 "skinMainView.tmpl"
} // end of template render
#line 93 "skinMainView.tmpl"
}; // end of class overview
#line 96 "skinMainView.tmpl"
struct clients :public master
#line 96 "skinMainView.tmpl"
{
#line 96 "skinMainView.tmpl"
content::clients &content;
#line 96 "skinMainView.tmpl"
clients(std::ostream &_s,content::clients &_content): master(_s,_content),content(_content)
#line 96 "skinMainView.tmpl"
{
#line 96 "skinMainView.tmpl"
}
#line 97 "skinMainView.tmpl"
virtual void render() {
#line 99 "skinMainView.tmpl"
out()<<" \n"
" <html>\n"
" ";
#line 99 "skinMainView.tmpl"
master::head();
#line 101 "skinMainView.tmpl"
out()<<"\n"
" <body>\n"
" ";
#line 101 "skinMainView.tmpl"
master::menu();
#line 111 "skinMainView.tmpl"
out()<<"\n"
" <table>\n"
" <thead>\n"
" <tr>\n"
" <td>ip</td>\n"
" <td>port</td>\n"
" <td>client remarks</td>\n"
" </tr>\n"
" </thead>\n"
" <tbody>\n"
" ";
#line 111 "skinMainView.tmpl"
for(int i=0; i<content.size; ++i){
#line 113 "skinMainView.tmpl"
out()<<"\n"
" <tr>\n"
" <td><a href=\"";
#line 113 "skinMainView.tmpl"
out()<<ROOT
#line 113 "skinMainView.tmpl"
out()<<"/comp/";
#line 113 "skinMainView.tmpl"
out()<<content.id.at(i);
#line 113 "skinMainView.tmpl"
out()<<"\">";
#line 113 "skinMainView.tmpl"
out()<<content.ip.at(i) ;
#line 114 "skinMainView.tmpl"
out()<<"</a></td>\n"
" <td>";
#line 114 "skinMainView.tmpl"
out()<<content.port.at(i) ;
#line 115 "skinMainView.tmpl"
out()<<"</td>\n"
" <td>";
#line 115 "skinMainView.tmpl"
out()<<content.remarks.at(i) ;
#line 117 "skinMainView.tmpl"
out()<<"</td>\n"
" </tr>\n"
" ";
#line 117 "skinMainView.tmpl"
}
#line 122 "skinMainView.tmpl"
out()<<"\n"
" </tbody>\n"
" </table>\n"
" </body> \n"
" <html> \n"
" ";
#line 122 "skinMainView.tmpl"
} // end of template render
#line 123 "skinMainView.tmpl"
}; // end of class clients
#line 125 "skinMainView.tmpl"
struct history :public master
#line 125 "skinMainView.tmpl"
{
#line 125 "skinMainView.tmpl"
content::history &content;
#line 125 "skinMainView.tmpl"
history(std::ostream &_s,content::history &_content): master(_s,_content),content(_content)
#line 125 "skinMainView.tmpl"
{
#line 125 "skinMainView.tmpl"
}
#line 126 "skinMainView.tmpl"
virtual void render() {
#line 128 "skinMainView.tmpl"
out()<<" \n"
" <html>\n"
" ";
#line 128 "skinMainView.tmpl"
master::head();
#line 130 "skinMainView.tmpl"
out()<<"\n"
" <body>\n"
" ";
#line 130 "skinMainView.tmpl"
master::menu();
#line 133 "skinMainView.tmpl"
out()<<"\n"
" <table>\n"
" <caption>\n"
" ";
#line 133 "skinMainView.tmpl"
out()<<cppcms::filters::escape(content.ip);
#line 133 "skinMainView.tmpl"
out()<<" ";
#line 133 "skinMainView.tmpl"
out()<<cppcms::filters::escape(content.port);
#line 133 "skinMainView.tmpl"
out()<<" (";
#line 133 "skinMainView.tmpl"
out()<<cppcms::filters::escape(content.remarks);
#line 133 "skinMainView.tmpl"
out()<<") - ";
#line 133 "skinMainView.tmpl"
out()<<cppcms::filters::escape(content.service);
#line 142 "skinMainView.tmpl"
out()<<"\n"
" </caption>\n"
" <thead>\n"
" <tr>\n"
" <td>timestamp</td>\n"
" <td>status</td>\n"
" </tr>\n"
" </thead>\n"
" <tbody>\n"
" ";
#line 142 "skinMainView.tmpl"
for(int i=0; i<content.size; ++i){
#line 143 "skinMainView.tmpl"
out()<<"\n"
" <tr class=\"";
#line 143 "skinMainView.tmpl"
out()<<content.status.at(i);
#line 144 "skinMainView.tmpl"
out()<<"\">\n"
" <td>";
#line 144 "skinMainView.tmpl"
out()<<content.timestamp.at(i) ;
#line 145 "skinMainView.tmpl"
out()<<"</td>\n"
" <td>";
#line 145 "skinMainView.tmpl"
out()<<content.status.at(i) ;
#line 147 "skinMainView.tmpl"
out()<<"</td>\n"
" </tr>\n"
" ";
#line 147 "skinMainView.tmpl"
}
#line 152 "skinMainView.tmpl"
out()<<"\n"
" </tbody>\n"
" </table>\n"
" </body> \n"
" <html> \n"
" ";
#line 152 "skinMainView.tmpl"
} // end of template render
#line 153 "skinMainView.tmpl"
}; // end of class history
#line 156 "skinMainView.tmpl"
} // end of namespace my_skin
#line 156 "skinMainView.tmpl"
namespace {
#line 156 "skinMainView.tmpl"
cppcms::views::generator my_generator;
#line 156 "skinMainView.tmpl"
struct loader {
#line 156 "skinMainView.tmpl"
loader() {
#line 156 "skinMainView.tmpl"
my_generator.name("my_skin");
#line 156 "skinMainView.tmpl"
my_generator.add_view<my_skin::master,cppcms::base_content>("master",true);
#line 156 "skinMainView.tmpl"
my_generator.add_view<my_skin::services,content::services>("services",true);
#line 156 "skinMainView.tmpl"
my_generator.add_view<my_skin::overview,content::overview>("overview",true);
#line 156 "skinMainView.tmpl"
my_generator.add_view<my_skin::clients,content::clients>("clients",true);
#line 156 "skinMainView.tmpl"
my_generator.add_view<my_skin::history,content::history>("history",true);
#line 156 "skinMainView.tmpl"
cppcms::views::pool::instance().add(my_generator);
#line 156 "skinMainView.tmpl"
}
#line 156 "skinMainView.tmpl"
~loader() { cppcms::views::pool::instance().remove(my_generator); }
#line 156 "skinMainView.tmpl"
} a_loader;
#line 156 "skinMainView.tmpl"
} // anon
| 11z-zpr-netspy | trunk/webend/skinMainView.cpp | C++ | gpl3 | 14,492 |
all: skins compile
dev: skins compile apacheRestart
compile: netspy.cpp constants.h skinMainView
c++ *.cpp -lcppcms -lcppdb -o netspy
skins: skinMainView
skinMainView: skinMainView.tmpl
cppcms_tmpl_cc skinMainView.tmpl -o skinMainView.cpp
apacheRestart:
sudo /etc/init.d/apache2 restart
clean:
rm netspy;
| 11z-zpr-netspy | trunk/webend/Makefile | Makefile | gpl3 | 325 |
#include <cppcms/view.h>
#include <string>
/**
* This namespace defines the structures used for information exchange between
* the controller and view.
*/
namespace content {
struct master : public cppcms::base_content{
};
struct overview : public cppcms::base_content {
int size;
std::vector<std::string> ip;
std::vector<std::string> comp_id;
std::vector<std::string> service_id;
std::vector<std::string> port;
std::vector<std::string> remarks;
std::vector<std::string> timestamp;
std::vector<std::string> service;
std::vector<std::string> status;
};
struct services : public cppcms::base_content {
int size;
std::vector<std::string> description;
std::vector<std::string> id;
};
struct clients : public cppcms::base_content{
int size;
std::vector<int> id;
std::vector<std::string> ip;
std::vector<std::string> port;
std::vector<std::string> remarks;
};
struct history : public cppcms::base_content{
int size;
std::string ip;
std::string port;
std::string remarks;
std::string service;
std::vector<std::string> timestamp;
std::vector<std::string> status;
};
} | 11z-zpr-netspy | trunk/webend/content.h | C++ | gpl3 | 1,334 |
function schedule_reload(){
setTimeout(reload, 3000);
}
function reload(){
window.location=window.location;
}
window.onload=schedule_reload(); | 11z-zpr-netspy | trunk/webend/script/default.js | JavaScript | gpl3 | 150 |
{
"service" : {
"api" : "fastcgi",
"socket" : "stdin" // use server's socket
}
}
| 11z-zpr-netspy | trunk/webend/config.js | JavaScript | gpl3 | 116 |
/**
* Defines the essential environment-dependent parameters
*/
#ifndef CONSTANTS_H
#define CONSTANTS_H
#define ROOT "/11z-zpr-netspy/webend/netspy";
#define USER "root"
#define DATABASE "netspy"
#define PASSWORD ""
#endif /* CONSTANTS_H */
| 11z-zpr-netspy | trunk/webend/constants.h | C | gpl3 | 247 |
#include <cppcms/application.h>
#include <cppcms/applications_pool.h>
#include <cppcms/service.h>
#include <cppcms/http_response.h>
#include <cppcms/url_dispatcher.h>
#include <iostream>
#include <cppdb/frontend.h>
#include <ctime>
#include "content.h"
#include "constants.h"
using namespace std;
/**
* Klasa aplikacji webowej.
* @param srv
*/
class netspy : public cppcms::application {
private:
cppdb::session sql;
public:
/**
* Konstruktor inicjalizujący routing oraz połączenie z bazą danych.
* @param srv
*/
netspy(cppcms::service &srv) : cppcms::application(srv) {
sql = cppdb::session(string("mysql:database=") + string(DATABASE) + string(";user=") + string(USER) + string(";password=") + string(PASSWORD));
dispatcher().assign("/service/(\\d+)/comp/(\\d+)", &netspy::history, this, 1, 2);
dispatcher().assign("/comp/(\\d+)/service/(\\d+)", &netspy::history, this, 2, 1);
dispatcher().assign("/overview", &netspy::overview, this);
dispatcher().assign("", &netspy::overview, this);
dispatcher().assign("/", &netspy::overview, this);
dispatcher().assign("/comp/(\\d+)", &netspy::overview_comp, this, 1);
dispatcher().assign("/service/(\\d+)", &netspy::overview_service, this, 1);
dispatcher().assign("/clients", &netspy::clientsList, this);
dispatcher().assign("/services", &netspy::servicesList, this);
}
virtual ~netspy() {
sql.close();
}
void overview() {
this->overview("");
}
void overview_comp(std::string comp) {
this->overview(std::string("record.client_id=") + comp);
}
void overview_service(std::string service) {
this->overview(std::string("record.service_id=") + service);
}
void overview(std::string condition) {
try {
std::string temp;
std::string query = "select * from record "
"right join (select max(timestamp) as last, client_id, service_id from record group by client_id, service_id) as refer on (record.timestamp=refer.last and record.client_id=refer.client_id and record.service_id=refer.service_id) "
"left join reply on (record.reply_id=reply._id) "
"left join service on (record.service_id = service._id) "
"left join client on (record.client_id = client._id)";
if ((&condition) != NULL && strlen(condition.c_str()) > 0) {
query += " where " + condition;
}
cppdb::statement stat = sql << query;
cppdb::result res = stat.query();
content::overview o;
o.size = stat.affected();
while (res.next()) {
o.ip.push_back(res.get<std::string > ("ip"));
o.port.push_back(res.fetch("port", temp) ? temp : "");
o.timestamp.push_back(res.get<std::string > ("timestamp"));
o.status.push_back(res.get<std::string > ("message"));
o.remarks.push_back(res.fetch("remarks", temp) ? temp : "");
o.service.push_back(res.get<std::string > ("description"));
o.comp_id.push_back(res.get<std::string > ("client_id"));
o.service_id.push_back(res.get<std::string > ("service_id"));
}
render("overview", o);
} catch (std::exception const &e) {
response().out() << e.what() << std::endl;
}
}
void servicesList() {
try {
content::services s;
cppdb::statement stat = sql << "SELECT * from service";
cppdb::result res = stat.query();
s.size = stat.affected();
while (res.next()) {
s.description.push_back(res.get<std::string > ("description"));
s.id.push_back(res.get<std::string > ("_id"));
}
render("services", s);
} catch (std::exception const &e) {
response().out() << "ERROR: " << e.what() << std::endl;
}
}
void clientsList() {
std::string temp;
try {
content::clients c;
cppdb::statement stat = sql << "SELECT * from client";
cppdb::result res = stat.query();
c.size = stat.affected();
while (res.next()) {
c.id.push_back(res.get<int>("_id"));
c.ip.push_back(res.get<std::string > ("ip"));
c.port.push_back(res.fetch("port", temp) ? temp : "");
c.remarks.push_back(res.fetch("remarks", temp) ? temp : "");
}
render("clients", c);
} catch (std::exception const &e) {
response().out() << "ERROR: " << e.what() << std::endl;
}
}
void history(std::string s_id, std::string c_id) {
try {
std::string temp;
std::string query = std::string("select * from record left join reply on (record.reply_id=reply._id) "
"left join client on (record.client_id=client._id) left join service on (record.service_id = service._id) where service_id=")
+ s_id + std::string(" and client_id=") + c_id + std::string(" order by timestamp desc");
cppdb::statement stat = sql << query;
cppdb::result res = stat.query();
content::history h;
h.size = stat.affected();
bool first_loop = true;
while (res.next()) {
if (first_loop) {
h.ip = res.get<std::string > ("ip");
h.port = res.fetch("port", temp) ? temp : "";
h.remarks = res.fetch("remarks", temp) ? temp : "";
h.service = res.get<std::string > ("description");
first_loop = false;
}
h.status.push_back(res.get<std::string > ("message"));
h.timestamp.push_back(res.get<std::string > ("timestamp"));
}
render("history", h);
} catch (std::exception const &e) {
std::cerr << "ERROR: " << e.what() << std::endl;
}
}
void dbtest() {
response().out() << "We will rock u <br />";
try {
cppdb::result res = sql << "SELECT * FROM client";
while (res.next()) {
int id = res.get<int>("_id");
std::string ip = res.get<std::string > ("ip");
response().out() << id << " " << ip << std::endl;
}
} catch (std::exception const &e) {
response().out() << "ERROR: " << e.what() << std::endl;
}
}
};
int main(int argc, char ** argv) {
try {
cppcms::service srv(argc, argv);
srv.applications_pool().mount(cppcms::applications_factory<netspy > ());
srv.run();
} catch (std::exception const &e) {
std::cerr << e.what() << std::endl;
}
}
| 11z-zpr-netspy | trunk/webend/netspy.cpp | C++ | gpl3 | 6,964 |
body{
background-color: gray;
}
caption{
background-color: black;
color: white;
}
table{
width: 800px;
margin-left: auto;
margin-right: auto;
border-collapse: collapse;
caption-side: top;
}
td{
padding-left: 5px;
padding-right: 5px;
}
thead{
text-align: left;
background-color: #222;
color: white;
}
table{
outline-style: dashed;
outline-width: 1px;
}
tr.alive{
background-color: lightgreen;
}
tr.dead{
background-color: lightcoral;
}
tr.none{
background-color: lightgoldenrodyellow;
}
A:link, A:hover, A:visited{
color: black;
text-decoration: underline;
}
A:hover{
color: white;
font-style: oblique;
}
div#menu{
margin-left: 50px;
margin-top: 0px;
float: left;
}
#menu ul{
list-style: armenian;
margin-top: 0px;
outline-style: dashed;
outline-width: 1px;
padding: 10px 30px 10px 30px;
} | 11z-zpr-netspy | trunk/webend/style/default.css | CSS | gpl3 | 912 |
#ifndef TYPES_HPP
#define TYPES_HPP
#include <boost/smart_ptr.hpp>
#include <boost/asio.hpp>
namespace netspy
{
typedef boost::shared_ptr<boost::asio::ip::tcp::socket> socket_ptr;
typedef char char_t;
typedef unsigned char uchar_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned int uint32_t;
const int DATA_MAX_LENGTH = 2056;
}
#endif
| 11z-zpr-netspy | trunk/server/Types.hpp | C++ | gpl3 | 412 |
#include "DataProxy.h"
#include <sstream>
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <vector>
#include <string>
#include <boost/thread.hpp>
#include "Config.hpp"
using namespace netspy::db;
using namespace std;
using namespace boost;
mutex DataProxy::singletonWatchdog;
shared_ptr<DataProxy> DataProxy::instance;
shared_ptr<DataProxy> DataProxy::getInstance(){
if(DataProxy::instance==NULL){
DataProxy::singletonWatchdog.lock();
if(DataProxy::instance==NULL){
Config & config = Config::getInstance();
DataProxy::instance = shared_ptr<DataProxy>(new DataProxy(
string(config.getDatabaseName()),
string(config.getDatabaseUser()),
string(config.getDatabasePass())
));
}
DataProxy::singletonWatchdog.unlock();
}
return DataProxy::instance;
}
DataProxy::DataProxy(string database, string user, string pass) {
this->db = cppdb::session("mysql:database=" + database + ";user=" + user + ";password=" + pass);
}
DataProxy::DataProxy(const DataProxy& orig) {
this->db = orig.db;
}
DataProxy::~DataProxy() {
db.close();
}
boost::shared_ptr<const std::vector<boost::shared_ptr<Client> > > DataProxy::getClients() const{
return resToClients(query("client"));
}
boost::shared_ptr<const vector<boost::shared_ptr<Reply> > > DataProxy::getReplies() const {
return resToReplies(query("reply"));
}
boost::shared_ptr<Client> DataProxy::getClient(unsigned int id) const{
return resToClient(query("client", "_id", boost::lexical_cast<string > (id)));
}
boost::shared_ptr<Client> DataProxy::getClient(string hash) const{
return resToClient(query("client", "hash", hash));
}
boost::shared_ptr<Service> DataProxy::getService(unsigned int id) const {
return resToService(query("service", "_id", boost::lexical_cast<string > (id)));
}
boost::shared_ptr<const vector<boost::shared_ptr<Service> > > DataProxy::getServices() const {
return resToServices(query("service"));
}
boost::shared_ptr<const vector<boost::shared_ptr<Service> > > DataProxy::getServices(string description) const {
return resToServices(query("service", "description", description));
}
boost::shared_ptr<const vector<boost::shared_ptr<Service> > > DataProxy::getServicesForClient(std::string hash) const {
boost::shared_ptr<Client> c = getClient(hash);
return getServicesForClient(c.get()!=NULL ? c->id : -1);
}
boost::shared_ptr<const vector<boost::shared_ptr<Service> > > DataProxy::getServicesForClient(unsigned int id) const {
boost::shared_ptr<cppdb::result> res = query(
"service left join client_service on(service._id=client_service.service_id)",
"is_active = TRUE and client_id",
boost::lexical_cast<string > (id)
);
return resToServices(res);
}
void DataProxy::setClientService(unsigned int client_id, unsigned int service_id, bool enable) {
resetQuery();
queryString << "select count(*) as number from client_service where client_id=" << client_id << " and service_id=" << service_id;
cppdb::statement stat = db << queryString.str();
cppdb::result res = stat.query();
res.next();
if (res.get<int>("number") > 0) {
resetQuery();
queryString << "update client_service set is_active=" << enable
<< " where service_id=" << service_id << " and client_id=" << client_id;
stat = db << queryString.str();
} else {
resetQuery();
queryString << "insert into client_service values (null," << client_id << "," <<
service_id << "," << enable << ")";
stat = db << queryString.str();
}
cout << "will exec: " << queryString.str() << endl;
stat.exec();
}
void DataProxy::setClientService(string client_hash, unsigned int service_id, bool enable) {
setClientService(getClient(client_hash)->id, service_id, enable);
}
void DataProxy::addRecord(unsigned int client_id, unsigned int service_id, unsigned int reply_id) {
resetQuery();
queryString << "insert into record values (null,now(),1," <<
client_id << "," << service_id << "," << reply_id << ")";
cppdb::statement stat = db << queryString.str();
stat.exec();
}
void DataProxy::addRecord(string client_hash, unsigned int service_id, unsigned int reply_id) {
addRecord(getClient(client_hash)->id, service_id, reply_id);
}
unsigned int DataProxy::addClient(std::string ip, unsigned short port, std::string hash, std::string remarks){
shared_ptr<Client> c = getClient(hash);
if(c.get()!=NULL){
return c->id;
}
else{
resetQuery();
queryString << "insert into client values (null,'"<<ip<<"',"<<port<<",'"<<hash<<"','"<<remarks<<"')";
cppdb::statement stat = db<<queryString.str();
stat.exec();
return getClient(hash)->id;
}
}
boost::shared_ptr<Service > DataProxy::resToService(boost::shared_ptr<cppdb::result> res) const{
Service* s = NULL;
if (res->next()) {
s=new Service();
res->fetch("_id", s->id);
res->fetch("description", s->description);
}
return boost::shared_ptr<Service>(s);;
}
boost::shared_ptr<const std::vector<boost::shared_ptr<Service> > > DataProxy::resToServices(boost::shared_ptr<cppdb::result> res) const {
shared_ptr<vector<shared_ptr<Service> > > v(new vector<shared_ptr<Service> >);
while (res->next()) {
v->push_back(shared_ptr<Service>(new Service()));
res->fetch("_id", (*(*v)[v->size()-1]).id);
res->fetch("description", (*(*v)[v->size()-1]).description);
}
return v;
}
shared_ptr<const vector<boost::shared_ptr<Reply> > > DataProxy::resToReplies(boost::shared_ptr<cppdb::result> res) const {
shared_ptr<vector<shared_ptr<Reply> > > v(new vector<shared_ptr<Reply> >);
while (res->next()) {
v->push_back(shared_ptr<Reply>(new Reply()));
res->fetch("_id", (*(*v)[v->size()-1]).id);
res->fetch("message", (*(*v)[v->size()-1]).message);
}
return v;
}
boost::shared_ptr<Client> DataProxy::resToClient(boost::shared_ptr<cppdb::result> res) const {
Client* c = NULL;
if (res->next()) {
c=new Client();
res->fetch("hash", c->hash);
res->fetch("_id", c->id);
res->fetch("ip", c->ip);
res->fetch("remarks", c->remarks);
res->fetch("port", c->port);
}
return boost::shared_ptr<Client>(c);
}
boost::shared_ptr<const std::vector<boost::shared_ptr<Client> > > DataProxy::resToClients(boost::shared_ptr<cppdb::result> res) const {
shared_ptr<vector<shared_ptr<Client> > > v(new vector<shared_ptr<Client> >);
while (res->next()) {
v->push_back(shared_ptr<Client>(new Client()));
res->fetch("_id", (*(*v)[v->size()-1]).id);
res->fetch("hash", (*(*v)[v->size()-1]).hash);
res->fetch("ip", (*(*v)[v->size()-1]).ip);
res->fetch("remarks", (*(*v)[v->size()-1]).remarks);
res->fetch("port", (*(*v)[v->size()-1]).port);
}
return v;
}
boost::shared_ptr<cppdb::result> DataProxy::query(string table) const{
return query(table, "", "");
}
boost::shared_ptr<cppdb::result> DataProxy::query(string table, string column, string value) const {
DataProxy * fake_this = const_cast<DataProxy*>(this);
fake_this->resetQuery();
fake_this->queryString << "select * from " << table;
if (column.length() > 0) {
fake_this->queryString << " where " << column << "='" << value << "'";
}
boost::shared_ptr<cppdb::result> res(new cppdb::result());
*res = fake_this->db << (fake_this->queryString.str());
return res;
}
void DataProxy::deleteClientsData(int client_id){
resetQuery();
queryString<<"delete from client_service where client_id="<<client_id<<"; ";
cppdb::statement stat = db << queryString.str();
stat.exec();
resetQuery();
queryString<<"delete from record where client_id="<<client_id<<"; ";
stat = db << queryString.str();
stat.exec();
resetQuery();
queryString<<"delete from client where _id="<<client_id<<";";
stat = db << queryString.str();
stat.exec();
resetQuery();
}
int DataProxy::addService(std::string description){
shared_ptr<const vector<shared_ptr<Service> > > matches = this->getServices(description);
if(matches.get()!=NULL && matches->size()>0){
return (*matches->begin())->id;
}else{
resetQuery();
queryString<<"insert into service values(null,'"<<description<<"')"<<endl;
cppdb::statement stat = db<<queryString.str();
stat.exec();
return this->addService(description);
}
}
| 11z-zpr-netspy | trunk/server/DataProxy.cpp | C++ | gpl3 | 8,704 |
#include "ClientRegistrar.hpp"
#include <boost/bind.hpp>
#include <boost/smart_ptr.hpp>
#include "JSONParser.hpp"
#include "Message.hpp"
#include "Types.hpp"
#include "ClientManager.hpp"
#include <cstdlib>
#include <sstream>
#include "Config.hpp"
using boost::asio::ip::tcp;
namespace netspy
{
void ClientRegistrar::setPort(const uint16_t &portNumber)
{
portNumber_=portNumber;
}
void ClientRegistrar::registerSession(socket_ptr sock)
{
try
{
char data[DATA_MAX_LENGTH];
memset(data,0,DATA_MAX_LENGTH);
boost::system::error_code error;
sock->read_some(boost::asio::buffer(data), error);
if (error == boost::asio::error::eof) return; // Connection closed cleanly by peer.
else if (error) throw boost::system::system_error(error); // Some other error.
Message message = JSONParser::unpack(data);
if (message.command.compare(getCommandString(REGISTER)) == 0)
{
if (Config::getInstance().isVerbose())
{
std::cout << "Received request" << std:: endl;
std::cout << "\tCommand: " << message.command << std::endl;
message.info.ip = sock->remote_endpoint().address().to_string();
std::cout << "\tHost info: " << "ip: " << message.info.ip << " port: " << message.info.port << std::endl;
std::cout << "\tHost info: " << "hash: " << message.info.hash << std:: endl;
std::string services;
for (ServiceList::const_iterator it=message.service_list.begin(); it != message.service_list.end(); ++it)
{
services += (*it);
services += std::string(" ");
}
std::cout << "\tHost info: " << "services_to_check: " << services << std::endl;
}
std::stringstream ss;
switch(ClientManager::getInstance().checkClient(message))
{
case ClientManager::NEW_CLIENT:
{
message.info.hash= ClientManager::getInstance().registerClient(message);
ss<<"NEW CLIENT - hash - " << message.info.hash << std::endl;
message.info.status = 1;
break;
}
case ClientManager::FORCE_NEW_CLIENT:
{
ss<<"FORCING CLIENT REGISTRATION"<<std::endl;
message.info.status = 2;
break;
}
case ClientManager::REUSE_CLIENT_HASH:
{
ss<<"CLIENT ALREADY REGISTERED - REUSING"<<std::endl;
message.info.status = 0;
break;
}
case ClientManager::CLIENT_REJECTED:
{
message.info.status = -1;
break;
}
}
if (Config::getInstance().isVerbose())
{
std::cout<<"Decision: " << ss.str();
}
}
else
{
message.command=getCommandString(UNKNOWN);
}
std::string answer=JSONParser::pack(message);
boost::asio::write(*sock,boost::asio::buffer(answer.c_str(),answer.length()));
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
}
}
void ClientRegistrar::registerProcess()
{
tcp::acceptor acceptor(registerService_, tcp::endpoint(tcp::v4(), portNumber_));
for (;;)
{
socket_ptr sock(new tcp::socket(registerService_));
acceptor.accept(*sock);
boost::thread t(&ClientRegistrar::registerSession,this, sock);
}
}
bool ClientRegistrar::run()
{
if (portNumber_ == 0) return false;
if (isRunning_) return false;
registerThread_ = boost::thread(&ClientRegistrar::registerProcess, this);
isRunning_ = true;
return true;
}
}
| 11z-zpr-netspy | trunk/server/ClientRegistrar.cpp | C++ | gpl3 | 3,477 |
#include "Message.hpp"
namespace netspy
{
const char * getCommandString(const Command &command)
{
switch(command)
{
case UNKNOWN: return NULL;
case REGISTER: return "register";
case CHECK_STATUS: return "check_status";
default:
return NULL;
}
}
}
| 11z-zpr-netspy | trunk/server/Message.cpp | C++ | gpl3 | 406 |
#ifndef CLIENT_REGISTRAR_HPP
#define CLIENT_REGISTRAR_HPP
#include "Types.hpp"
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
namespace netspy
{
/**
* @brief Obsługuje rejestrację klientów
*
* Klasa obsługuje połączenia przychodzące - rejestrację klientów (w osobnych wątkach). Zaimplementowana jako singlegon.
*
*/
class ClientRegistrar
{
public:
static ClientRegistrar &getInstance()
{
static ClientRegistrar registrar;
return registrar;
}
/**
*
* Ustawia numer portu na którym serwer ma oczekiwać na rejestrację
*
*/
void setPort(const uint16_t &portNumber);
bool run();
private:
ClientRegistrar():isRunning_(false),portNumber_(0) {}
ClientRegistrar(const ClientRegistrar &);
ClientRegistrar& operator=(const ClientRegistrar&);
/**
* Nasłuchuje na połaczenie
*/
void registerProcess();
/// Funkcja obsługująca sesję komunikacji, działa w osobnym wątku, odpalana w momencie przyjęcia połączenia
void registerSession(socket_ptr sock);
bool isRunning_;
boost::asio::io_service registerService_;
uint16_t portNumber_;
boost::thread registerThread_;
};
}
#endif
| 11z-zpr-netspy | trunk/server/ClientRegistrar.hpp | C++ | gpl3 | 1,238 |
#ifndef CLIENT_CHECKER_HPP
#define CLIENT_CHECKER_HPP
#include <boost/thread.hpp>
namespace netspy
{
/**
* Klasa opakowujaca wątki odpytujące klientów
*/
class ClientChecker
{
public:
static ClientChecker & getInstance()
{
static ClientChecker checker;
return checker;
}
/**
* Uruchamia zadaną ilość wątków obsługujących zapytania o stan klientów
*/
void runCheckers(unsigned int checkersAmount);
/**
* Obsługuje proces sesji komunikacyjnej z klientem. Opalany w osobnym wątku. Oczekuje na zgłoszenia na kolejce reqeustów,
* za pomocą interfejsu klasy RequestManager.
*/
void checkerSession();
private:
ClientChecker(ClientChecker &cl);
ClientChecker():isRunning_(false){};
bool isRunning_;
boost::thread_group checkerGroup_;
};
}
#endif
| 11z-zpr-netspy | trunk/server/ClientChecker.hpp | C++ | gpl3 | 873 |
#ifndef MESSAGE_HPP
#define MESSAGE_HPP
#include<string>
#include "Structures.hpp"
#include <boost/unordered_map.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
using namespace netspy::db;
namespace netspy
{
enum Command
{
UNKNOWN=0,
REGISTER,
CHECK_STATUS
};
const char * getCommandString(const Command &command);
typedef std::vector<std::string> ServiceList;
typedef boost::unordered_map<std::string,int> ServiceStatus;
struct Message
{
std::string command;
Client info;
ServiceList service_list;
ServiceStatus status_map;
};
typedef boost::shared_ptr<Message> message_ptr;
}
#endif
| 11z-zpr-netspy | trunk/server/Message.hpp | C++ | gpl3 | 656 |
#ifndef STRUCTURES_HPP
#define STRUCTURES_HPP
#include <string>
namespace netspy
{
namespace db
{
struct Client
{
unsigned int id;
std::string ip;
std::string hash;
unsigned short port;
std::string remarks;
int status; // for communication purposes
};
struct Service
{
unsigned int id;
std::string description;
};
struct Reply
{
unsigned int id;
std::string message;
};
}
}
#endif
| 11z-zpr-netspy | trunk/server/Structures.hpp | C++ | gpl3 | 569 |
#include "Message.hpp"
#include "DataTypes.hpp"
#include "boost/shared_ptr.hpp"
#include "boost/thread.hpp"
namespace netspy
{
class RequestManager
{
public:
static RequestManager & getInstance()
{
static RequestManager requestManager;
return requestManager;
}
/// do pobierania wiadomości przez wątek
shared_msg getRequest();
/// do zapisu wiadomości
void storeResult(shared_msg result);
void run();
private:
/// wiadomości otrzymane od klientów
MessageQueue results_;
/// wiadomości wysłane do klientów
MessageQueue requests_;
void generateRequests();
void saveResults();
bool isRunning_;
client_vec_ptr clients;
service_vec_ptr services;
client_service_map_ptr serviceMap;
boost::thread requestHandler_;
boost::thread resultHandler_;
RequestManager():isRunning_(false){}
RequestManager(RequestManager &req);
RequestManager& operator=(const RequestManager&);
};
}
| 11z-zpr-netspy | trunk/server/RequestManager.hpp | C++ | gpl3 | 1,006 |
#ifndef CLIENT_MANAGER_HPP
#define CLIENT_MANAGER_HPP
#include "DataTypes.hpp"
#include "Message.hpp"
#include <string>
#include <boost/thread/mutex.hpp>
namespace netspy
{
/**
* @brief Klasa odpowiedzialna za bufforowanie klientów. Dostarcza interfejsy umożliwiające
* rejestrację nowych klientów, sprawdzenie czy klient jest aktualnie w bazie danych
*
*/
class ClientManager
{
public:
/**
Możliwe statusy przyjęcia klienta
*/
enum RegisterStatus
{
CLIENT_REJECTED = -1, /// odrzucenie klienta
NEW_CLIENT = 0, /// rejestracja nowego klienta
FORCE_NEW_CLIENT = 1, /// wymuszenie ponownej rejestracij
REUSE_CLIENT_HASH = 2 /// reużycie sesji
};
static ClientManager & getInstance()
{
static ClientManager clientManager;
return clientManager;
}
/**
Funkcja inicjująca bufor zawartością bazy danych
*/
void initialize();
/**
@return
*/
RegisterStatus checkClient(const Message &message);
/**
@return
*/
std::string registerClient(const Message &message);
/**
Sprawdza stan ostatniej rejestracji
@return zwraca true, jeśli odbyła się rejestracja nowego klienta
*/
bool isClientUpdated() const;
bool isServiceUpdated() const;
client_vec_ptr getClients();
service_vec_ptr getServices();
client_service_map_ptr getClientServiceMap();
private:
ClientManager(){};
ClientManager(ClientManager &cm);
ClientManager& operator=(const ClientManager&);
/**
Funkcja generuje losowy hash dla nowo rejestrowanych klientów.
@return Zwraca 32znakowy string z hashem.
*/
std::string generateHash();
boost::mutex resouceMutex_;
volatile bool isClientUpdated_;
volatile bool isServiceUpdated_;
client_vec_ptr clientBuffer_;
service_vec_ptr serviceBuffer_;
client_service_map_ptr serviceMapBuffer_;
};
}
#endif
| 11z-zpr-netspy | trunk/server/ClientManager.hpp | C++ | gpl3 | 1,995 |
#-------- DEFAULT ---------------------------
flags = ['-O2','-Wall','-pedantic']
lib_boost = ['boost_system', 'boost_thread','boost_random','boost_program_options']
lib_cppcms = ['cppcms','cppdb']
libs = lib_boost + lib_cppcms
env = Environment(CPPFLAGS=flags, LIBS=libs)
netspy = 'netspy-server'
dbtest = 'dbtest'
sources = Split("""
main.cpp
Message.cpp
JSONParser.cpp
ClientRegistrar.cpp
RequestManager.cpp
Config.cpp
ClientChecker.cpp
ClientManager.cpp
DataProxy.cpp
""")
dbtestSources = Split("""
DataProxy.cpp
Config.cpp
DataTest.cpp
""")
targets = {
netspy : sources,
dbtest : dbtestSources
}
default = env.Program( target=netspy, source = env.Object(targets[netspy]) )
Default(default)
env.Program(target=dbtest, source = env.Object(targets[dbtest]))
| 11z-zpr-netspy | trunk/server/SConstruct | Python | gpl3 | 781 |
#include "ClientManager.hpp"
#include "DataProxy.h"
//#include <boost/random/random_device.hpp>
//#include <boost/random/uniform_int_distribution.hpp>
#include "DataProxy.h"
#include <boost/nondet_random.hpp>
#include <sstream>
namespace netspy
{
bool ClientManager::isClientUpdated() const
{
return isClientUpdated_;
}
bool ClientManager::isServiceUpdated() const
{
return isServiceUpdated_;
}
std::string ClientManager::generateHash()
{
std::string chars(
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"1234567890"
"!@#$%^&*()"
"~-_=+[{]{,<.>/? ");
boost::random_device rng;
std::stringstream str;
for(int i = 0; i < 32; ++i) {
str << chars[rng()%chars.length()];
}
return str.str();
}
void ClientManager::initialize()
{
clientBuffer_ = client_vec_ptr(new client_vec());
serviceBuffer_ = service_vec_ptr(new service_vec());
serviceMapBuffer_ = client_service_map_ptr(new client_service_map());
boost::shared_ptr <DataProxy> db = DataProxy::getInstance();
boost::shared_ptr<const std::vector<boost::shared_ptr<Client> > > clients = db->getClients();
for(client_vec::const_iterator it=clients->begin(); it!=clients->end(); ++it)
{
clientBuffer_->push_back(*it);
}
boost::shared_ptr<const std::vector<boost::shared_ptr<Service> > > services = db->getServices();
if (services.get()!=NULL)
{
for(service_vec::const_iterator it=services->begin(); it!=services->end(); ++it)
{
serviceBuffer_->push_back(*it);
}
}
for(client_vec::const_iterator it=clients->begin(); it!=clients->end(); ++it)
{
boost::shared_ptr<const std::vector<boost::shared_ptr<Service> > > clientServices = db->getServicesForClient((*it)->id);
service_vec_ptr clientNewServices(new service_vec());
for(service_vec::const_iterator cs=clientServices->begin(); cs!=clientServices->end(); ++cs)
{
for(service_vec::const_iterator as=serviceBuffer_->begin(); as!=serviceBuffer_->end(); ++as)
{
if ((*cs)->description.compare((*as)->description)==0)
{
clientNewServices->push_back((*as));
}
}
}
serviceMapBuffer_->insert(make_pair((*it)->hash,clientNewServices));
}
}
ClientManager::RegisterStatus ClientManager::checkClient(const Message &message)
{
if (message.info.hash.empty()) return NEW_CLIENT;
boost::mutex::scoped_lock (resourceMutex_);
for(client_vec::const_iterator it=clientBuffer_->begin(); it!=clientBuffer_->end(); ++it)
{
if ((*it)->hash.compare(message.info.hash) == 0)
{
isClientUpdated_=true;
return REUSE_CLIENT_HASH;
}
}
return FORCE_NEW_CLIENT;
}
std::string ClientManager::registerClient(const Message &message)
{
boost::mutex::scoped_lock (resouceMutex_);
for(client_vec::const_iterator it=clientBuffer_->begin(); it!=clientBuffer_->end(); ++it)
{
if ((*it)->hash.compare(message.info.hash) == 0)
return std::string("");
}
client_ptr newClient(new Client(message.info));
newClient->hash = generateHash();
boost::shared_ptr <DataProxy> db = DataProxy::getInstance();
newClient->id = db->addClient(newClient->ip,newClient->port,newClient->hash,newClient->remarks);
clientBuffer_->push_back(newClient);
bool knownService = false;
service_vec_ptr clientService(new service_vec());
for(std::vector<std::string>::const_iterator it=message.service_list.begin(); it!=message.service_list.end(); ++it)
{
for(service_vec::const_iterator s=serviceBuffer_->begin(); s!=serviceBuffer_->end(); ++s)
{
if ((*it).compare((*s)->description) == 0 )
{
knownService = true;
clientService->push_back((*s));
db->setClientService(newClient->id,(*s)->id,true);
break;
}
}
if (!knownService)
{
service_ptr service(new Service());
service->description = (*it);
service->id=db->addService(service->description);
serviceBuffer_->push_back(service);
clientService->push_back(service);
db->setClientService(newClient->id,service->id,true);
}
}
serviceMapBuffer_->insert(make_pair(newClient->hash,clientService));
std::cout<<serviceMapBuffer_->size()<<std::endl;
isClientUpdated_ = true;
isServiceUpdated_ = true;
return newClient->hash;
}
client_vec_ptr ClientManager::getClients()
{
boost::mutex::scoped_lock (resourceMutex_);
client_vec_ptr clients(new client_vec());
for (client_vec::const_iterator it=clientBuffer_->begin(); it!=clientBuffer_->end(); ++it)
{
clients->push_back((*it));
}
isClientUpdated_ = false;
return clients;
}
client_service_map_ptr ClientManager::getClientServiceMap()
{
return serviceMapBuffer_;
}
service_vec_ptr ClientManager::getServices()
{
boost::mutex::scoped_lock (resourceMutex_);
service_vec_ptr services(new service_vec());
if (serviceBuffer_.get()!=NULL)
{
for (service_vec::const_iterator it=serviceBuffer_->begin(); it!=serviceBuffer_->end(); ++it)
{
services->push_back((*it));
}
}
isServiceUpdated_ = false;
return services;
}
}
| 11z-zpr-netspy | trunk/server/ClientManager.cpp | C++ | gpl3 | 5,120 |
#include "Config.hpp"
#include <boost/program_options.hpp>
namespace po = boost::program_options;
namespace netspy
{
Config::Config()
{
setDefaultValues();
}
void Config::parseCommandLine(int argc, char *argv[]) throw (int)
{
po::options_description desc("Available options");
desc.add_options()
("help", "prints this help")
("interval", po::value<unsigned int>(), "sets interval time (should be given in seconds)")
("verbose", "sets verbose mode -> server printouts everything he can ")
("port",po::value<unsigned int>(), "changes registration port (default = 5000) ")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
throw 0;
}
if (vm.count("interval"))
{
checkPeriod_ = vm["interval"].as<unsigned int>();
}
if (vm.count("verbose"))
{
isVerbose_=true;
}
if(vm.count("port"))
{
registerPort_ = vm["port"].as<unsigned int>();
}
}
void Config::setDefaultValues()
{
checkPeriod_ = defaultCheckPeriod;
registerPort_ = defaultRegisterPort;
isVerbose_ = defaultVerbose;
checkerThreadNumber_ = defaultCheckerThreadNumber;
databaseName_ = defaultDatabaseName();
databaseUser_ = defaultDatabaseUser();
databasePass_ = defaultDatabasePass();
}
bool Config::isVerbose() const {
return isVerbose_;
}
uint32_t Config::getCheckPeriod() const {
return checkPeriod_;
}
uint16_t Config::getRegisterPort() const {
return registerPort_;
}
const char * Config::getDatabaseName() const{
return databaseName_;
}
const char * Config::getDatabasePass() const {
return databasePass_;
}
const char * Config::getDatabaseUser() const {
return databaseUser_;
}
uint32_t Config::getCheckerThreadNumber() const
{
return checkerThreadNumber_;
}
}
| 11z-zpr-netspy | trunk/server/Config.cpp | C++ | gpl3 | 1,845 |
#include "ClientChecker.hpp"
#include <cstdlib>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include "Types.hpp"
#include <cstdlib>
#include "Message.hpp"
#include "JSONParser.hpp"
#include "RequestManager.hpp"
#include "Config.hpp"
using boost::asio::ip::tcp;
namespace netspy
{
void ClientChecker::runCheckers(uint32_t checkerThreadNumber)
{
if (!isRunning_)
{
for (uint32_t i=0; i<checkerThreadNumber; ++i)
{
checkerGroup_.create_thread(boost::bind(&ClientChecker::checkerSession,this));
}
}
isRunning_= true;
}
void ClientChecker::checkerSession()
{
for(;;)
{
message_ptr message = RequestManager::getInstance().getRequest();
message->command=getCommandString(CHECK_STATUS);
message_ptr ans(new Message((*message)));
if(Config::getInstance().isVerbose())
{
std::cout << "Sending command" << std:: endl;
std::cout << "\tCommand: " << message->command << std::endl;
std::cout << "\tHost info: " << "ip: " << message->info.ip << " port: " << message->info.port << std::endl;
std::cout << "\tHost info: " << "hash: " << message->info.hash << std:: endl;
}
try{
boost::asio::io_service io_service;
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(message->info.ip), message->info.port);
socket_ptr sock(new tcp::socket(io_service));
sock->connect(endpoint);
std::string query = JSONParser::pack((*message));
boost::asio::write((*sock), boost::asio::buffer(query.c_str(),query.length()));
char data[DATA_MAX_LENGTH];
memset(data,0,DATA_MAX_LENGTH);
boost::system::error_code error;
sock->read_some(boost::asio::buffer(data), error);
if (error) throw boost::system::system_error(error); // Some other error.
ans = message_ptr(new Message(JSONParser::unpack(data)));
ans->info.hash=message->info.hash;
if(Config::getInstance().isVerbose())
{
for (ServiceList::const_iterator it=ans->service_list.begin(); it != ans->service_list.end(); ++it)
{
std::cout << "\tHost info: " << "Service: " << (*it) << " Status: " << ans->status_map[(*it)] << std::endl;
}
}
RequestManager::getInstance().storeResult(ans);
}
catch (std::exception& e)
{
// std::cerr << "Exception: " << e.what() << "\n";
ans->service_list.clear();
if (Config::getInstance().isVerbose())
{
std::cout << "\tHost info: dead" << std::endl;
RequestManager::getInstance().storeResult(ans);
}
}
}
}
}
| 11z-zpr-netspy | trunk/server/ClientChecker.cpp | C++ | gpl3 | 2,681 |
#ifndef JSON_PARSER_HPP
#define JSON_PARSER_HPP
#include "Message.hpp"
#include <string>
namespace netspy
{
/**
* Klasa parsująca stringi na obiekty JSON a następnie na wewnętrzne struktury rozumiane przez aplikację i na odwrót.
*
*/
class JSONParser
{
public:
/**
* @return zwraca strukturę Message zbudowaną na podstawie stringu
*/
static Message unpack(const std::string &stringMessage);
/**
* @return zwraca string zserializowanego obiektu JSON powstałego na bazie Message
*/
static std::string pack(const Message &message);
};
}
#endif
| 11z-zpr-netspy | trunk/server/JSONParser.hpp | C++ | gpl3 | 666 |
#ifndef DATA_TYPES_HPP
#define DATA_TYPES_HPP
#include "Types.hpp"
#include "Structures.hpp"
#include "Message.hpp"
#include "SynchronizedQueue.hpp"
#include <boost/shared_ptr.hpp>
#include <vector>
#include <map>
namespace netspy
{
typedef boost::shared_ptr<Reply> reply_ptr;
typedef boost::shared_ptr<Client> client_ptr;
typedef boost::shared_ptr<Service> service_ptr;
typedef boost::shared_ptr<Message> message_ptr;
typedef std::vector<reply_ptr> reply_vec;
typedef std::vector<client_ptr> client_vec;
typedef std::vector<service_ptr> service_vec;
typedef std::vector<message_ptr> message_vev;
typedef boost::shared_ptr<service_vec> service_vec_ptr;
typedef boost::shared_ptr<client_vec> client_vec_ptr;
typedef std::map<std::string,service_vec_ptr> client_service_map;
typedef boost::shared_ptr<client_service_map> client_service_map_ptr;
typedef boost::shared_ptr<Message> shared_msg;
typedef SynchronizedQueue<shared_msg> MessageQueue;
}
#endif
| 11z-zpr-netspy | trunk/server/DataTypes.hpp | C++ | gpl3 | 977 |
#include "RequestManager.hpp"
#include "ClientManager.hpp"
#include "Message.hpp"
#include "DataProxy.h"
#include "Config.hpp"
#include <boost/thread/thread.hpp>
namespace netspy
{
void RequestManager::generateRequests()
{
for(;;)
{
boost::this_thread::sleep(boost::posix_time::seconds(Config::getInstance().getCheckPeriod()));
if (ClientManager::getInstance().isClientUpdated())
{
clients = ClientManager::getInstance().getClients();
serviceMap = ClientManager::getInstance().getClientServiceMap();
}
for(client_vec::const_iterator it=clients->begin(); it!=clients->end(); ++it)
{
Message *message = new Message();
message->command=getCommandString(CHECK_STATUS);
message->info=(*(*it));
message_ptr mess(message);
requests_.push(mess);
}
}
}
void RequestManager::saveResults()
{
for(;;)
{
boost::shared_ptr <DataProxy> db = DataProxy::getInstance();
message_ptr mess;
results_.waitAndPop(mess);
if (ClientManager::getInstance().isServiceUpdated())
{
services = ClientManager::getInstance().getServices();
serviceMap = ClientManager::getInstance().getClientServiceMap();
}
service_vec_ptr ss = (*serviceMap)[mess->info.hash];
if(mess->service_list.empty())
{
for (service_vec::const_iterator it=ss->begin(); it!=ss->end(); ++it)
{
db->addRecord(mess->info.hash, (*it)->id, 2);
}
}
else
{
for (service_vec::const_iterator it=ss->begin(); it!=ss->end(); ++it)
{
db->addRecord(mess->info.hash, (*it)->id, 1);
}
}
}
}
shared_msg RequestManager::getRequest()
{
shared_msg request;
requests_.waitAndPop(request);
return request;
}
void RequestManager::storeResult(shared_msg result)
{
results_.push(result);
}
void RequestManager::run()
{
if(!isRunning_)
{
clients = ClientManager::getInstance().getClients();
services = ClientManager::getInstance().getServices();
serviceMap = ClientManager::getInstance().getClientServiceMap();
requestHandler_ = boost::thread(boost::bind(&RequestManager::generateRequests,this));
resultHandler_= boost::thread(boost::bind(&RequestManager::saveResults,this));
}
isRunning_=true;
}
}
| 11z-zpr-netspy | trunk/server/RequestManager.cpp | C++ | gpl3 | 2,472 |
#include <cppcms/json.h>
#include <iostream>
#include <sstream>
#include "JSONParser.hpp"
using namespace netspy;
namespace cppcms {
namespace json {
//
// We specilize cppcms::json::traits structure to convert
// objects to and from json values
//
template<>
struct traits<Message> {
// this function should throw
// cppcms::json::bad_value_cast in case
// of invalid or impossible conversion,
// this would give an easy way to substitute
// a default value in case of fault
static Message get(value const &v)
{
Message message;
if(v.type()!=is_object)
throw bad_value_cast();
message.command=v.get<std::string>("command");
if (message.command.compare("register") == 0 )
{
if (v.find("payload.hash").type() == is_string)
{
message.info.hash = v.get<std::string>("payload.hash");
}
else if (v.find("payload.hash").type() == is_null)
{
message.info.hash = std::string("");
}
if (v.find("payload.port").type() == is_string)
{
message.info.port = atoi(v.get<std::string>("payload.port").c_str());
}
else
{
message.info.port = v.get<unsigned short>("payload.port");
}
message.service_list = v.get<std::vector<std::string> >("payload.service_list");
return message;
}
else if (message.command.compare("check_status") == 0 )
{
std::vector<value> values = v.get<std::vector<value> >("payload.check_result");
for(std::vector<value>::const_iterator it=values.begin(); it!=values.end(); it++)
{
message.service_list.push_back((* (*it).object().begin()).first.str());
message.status_map.insert(std::make_pair((* (*it).object().begin()).first.str(),(* (*it).object().begin()).second.get_value<int>()));
}
}
return message;
}
static void set(value &v, Message const &in)
{
v.set("command",in.command);
if (in.command.compare("register") == 0)
{
v.set("payload.hash",in.info.hash);
v.set("payload.status",in.info.status);
}
else if (in.command.compare("check_status") == 0)
{
}
}
};
} // json
} // cppcms
namespace netspy
{
Message JSONParser::unpack(const std::string &stringMessage)
{
std::stringstream mess(stringMessage);
cppcms::json::value object;
object.load(mess,true);
return object.get_value<Message>();
}
std::string JSONParser::pack(const Message &message)
{
std::stringstream result;
cppcms::json::value object = message;
result << object;
return result.str();
}
int json_test()
{
cppcms::json::value my_object;
cppcms::json::value inner_object;
inner_object["hash"]="1";
inner_object["status"]=0;
inner_object["port"]=6666;
inner_object["service_list"][0]="alive";
inner_object["service_list"][1]="ftp";
// Create object data
my_object["command"]="register";
my_object["payload"]=inner_object;
// Get values using path.
std::string name=my_object.get<std::string>("command");
// load person object from the object
// using above traits
Message request = my_object.get_value<Message>();
std::cout << "Req.command = " << request.command << std::endl;
std::cout << "Req.info: hash = " << request.info.hash << " port = " << request.info.port << std::endl;
std::cout << "Pack test: " << JSONParser::pack(request) << std::endl;
// save person object to json objectdd
cppcms::json::value other = request;
// write data to output
std::cout << other << std::endl;
// write data formatter nicely
my_object.save(std::cout,cppcms::json::readable);
// save object to stream and load it back
std::stringstream tmp;
tmp << my_object;
cppcms::json::value reloaded;
reloaded.load(tmp,true);
return 0;
}
}
| 11z-zpr-netspy | trunk/server/JSONParser.cpp | C++ | gpl3 | 4,007 |
#ifndef DATAPROXY_H
#define DATAPROXY_H
#include <cppdb/frontend.h>
#include <vector>
#include <sstream>
#include <boost/shared_ptr.hpp>
#include "Structures.hpp"
#include <boost/thread.hpp>
namespace netspy {
namespace db {
/**
* Klasa umożliwiająca komunikację z bazą danych w zakresie określonym specyfiką aplikacji.
* Pozwala uzyskać informacje o wszystkich klientach (komputerach), usługach oraz potencjalnych
* odpowiedziach zwracanych przez klientów.
*/
class DataProxy {
public:
/**
* Zwraca shared_ptr do obiektu pośrednika bazodanowego
* @return shared_ptr<DataProxy>
*/
static boost::shared_ptr<DataProxy> getInstance();
virtual ~DataProxy();
/**
* Pozwala pobrać informację o wszystkich odpowiedziach zdefiniowanych w bazie danych.
* @return wskaźnik do wektora wskaźników na obiekty struktury Reply
*/
boost::shared_ptr<const std::vector<boost::shared_ptr<Reply> > > getReplies() const;
/**
* Pozwala pobrać informację o zarejestrowanych klientach
* @return wskaźnik na wektor wskaźników na obiekty struktury Client
*/
boost::shared_ptr<const std::vector<boost::shared_ptr<Client> > > getClients() const;
/**
* Pozwala pobrać informację o kliencie identyfikowanym numerem id
* @param id numer id z bazy danych
* @return wskaźnik na obiekt struktury Client
*/
boost::shared_ptr<Client> getClient(unsigned int id) const;
/**
* Pozwala pobrać informację o kliencje identyfikowanym jego hashem
* @param hash hash przypisany klientowi
* @return wskaźnik do struktury Client
*/
boost::shared_ptr<Client> getClient(std::string hash) const;
/**
* Pozwala pobrać informację o wszystkich usługach, pod kątem których odpytywani są klienci
* @return Wskaźnik na wektor wskaźników na obiekty struktury Service
*/
boost::shared_ptr<const std::vector<boost::shared_ptr<Service> > > getServices() const;
/**
* Pozwala pobrać informację o wybranej, określonej numerem id usłudze.
* @param id numer id przypisany danej usłudze
* @return wskaźnik na obiekt struktury Service
*/
boost::shared_ptr<Service> getService(unsigned int id) const;
/**
* Pozwala pobrać informację o usługach o podanym opisie
* @param description opis usług zapisany w bazie danych
* @return wskaźnik na wektor wskaźników do obiektów struktury Service
*/
boost::shared_ptr<const std::vector<boost::shared_ptr<Service> > > getServices(std::string description) const;
/**
* Pozwala pobrać informację o aktywnych usługach świadczonych przez danego klienta.
* @param hash hash identyfikujący klienta
* @return wskaźnik na wektor wskaźników do obiektów struktury Service
*/
boost::shared_ptr<const std::vector<boost::shared_ptr<Service> > > getServicesForClient(std::string hash) const;
/**
* Pozwala pobrać informację o aktywnych usługach świadczonych przez danego klienta.
* @param id numer id klienta zapisany w bazie danych
* @return wskaźnik na wektor wskaźników do obiektów struktury Service
*/
boost::shared_ptr<const std::vector<boost::shared_ptr<Service> > > getServicesForClient(unsigned int id) const;
/**
* Pozwala skojarzyć klienta z określoną usługą lub zmienić status usługi już klientowi przypisanyej
* @param client_id id klienta
* @param service_id id usługi
* @param enable prawda, jeśli chcemy, aby usługa była aktywowana
* @return
*/
void setClientService(unsigned int client_id, unsigned int service_id, bool enable);
/**
* Pozwala skojarzyć klienta z określoną usługą lub zmienić status usługi już klientowi przypisanyej
* @param client_hash hash klienta
* @param service_id id usługi
* @param enable prawda, jeśli chcemy, aby usługa była aktywowana
* @return
*/
void setClientService(std::string client_hash, unsigned int service_id, bool enable);
/**
* Pozwala dodać do bazy danych elementarny zapis o dostępności określonej usługi na określonym komputerze
* @param client_id id klienta
* @param service_id id usługi
* @param reply_id kod odpowiedzi
* @return
*/
void addRecord(unsigned int client_id, unsigned int service_id, unsigned int reply_id);
/**
* Pozwala dodać do bazy danych elementarny zapis o dostępności określonej usługi na określonym komputerze
* @param client_hash hash klienta
* @param service_id numer id klienta
* @param reply_id kod odpowiedzi
* @return
*/
void addRecord(std::string client_hash, unsigned int service_id, unsigned int reply_id);
/**
* Usuwa wszystkie przechowywane informacje o danym kliencie
* @param client_id
*/
void deleteClientsData(int client_id);
/**
* Pozwala wprowadzić nową usługę do bazy, o ile usługa o podanym opisie nie zostanie znaleziona.
* W obu przypadkach zwraca id usługi.
* @param description opis nowo dodawanej usługi
* @return
*/
int addService(std::string description);
/**
* Opakowuje procedurę rejestracji klienta w bazie danych. Dla nowych klientów dodaje wpis i zwraca id klienta,
* zaś w przypadku natrafienia na klienta o podanym hashu - zwraca jego id z bazy.
* @param ip
* @param port
* @param hash hash klienta
* @param remarks opis, komentarz
* @return przydzielony nowemu klientowi numer id. -1 - błąd
*/
unsigned int addClient(std::string ip, unsigned short port, std::string hash, std::string remarks);
private:
static boost::shared_ptr<DataProxy> instance;
static boost::mutex singletonWatchdog;
/**
*
* @param database nazwa bazy danych
* @param user nazwa użytkownika
* @param pass hasło dostępu do bazy danych
*/
DataProxy(std::string database, std::string user, std::string pass);
DataProxy(const DataProxy& orig);
cppdb::session db;
std::stringstream queryString;
boost::shared_ptr<Service> resToService(boost::shared_ptr<cppdb::result> res) const;
boost::shared_ptr<const std::vector<boost::shared_ptr<Service> > > resToServices(boost::shared_ptr<cppdb::result> res) const;
boost::shared_ptr<const std::vector<boost::shared_ptr<Reply> > > resToReplies(boost::shared_ptr<cppdb::result> res) const;
boost::shared_ptr<Client> resToClient(boost::shared_ptr<cppdb::result> res) const;
boost::shared_ptr<const std::vector<boost::shared_ptr<Client> > > resToClients(boost::shared_ptr<cppdb::result> res) const;
boost::shared_ptr<cppdb::result> query(std::string table) const;
boost::shared_ptr<cppdb::result> query(std::string table, std::string column, std::string value) const;
void resetQuery(){
queryString.clear();
queryString.str("");
}
};
}
}
#endif /* DATAPROXY_H */
| 11z-zpr-netspy | trunk/server/DataProxy.h | C++ | gpl3 | 8,325 |
#include <cstdlib>
#include "DataProxy.h"
#include "Structures.hpp"
//#include "Request.hpp"
#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;
using namespace netspy::db;
using namespace boost;
void queryAll(shared_ptr<DataProxy> db) {
//get all clients
int i = 1;
shared_ptr<Client> c;
while (c.get()!=NULL){
c = db->getClient(i++);
cout << c->ip << ", " << c->remarks << endl;
}
//get all services
cout << "getting all services" << endl;
shared_ptr<const vector<shared_ptr<netspy::db::Service> > > v = db->getServices();
for (vector<shared_ptr<netspy::db::Service> >::const_iterator iter = v->begin(); iter != v->end(); ++iter) {
cout << (*iter)->id << ": " << (*iter)->description << endl;
}
cout << "getting pings" << endl;
v = db->getServices("ping");
for (vector<shared_ptr<netspy::db::Service> >::const_iterator iter = v->begin(); iter != v->end(); ++iter) {
cout << (*iter)->id << ": " << (*iter)->description << endl;
}
cout << "getting services for client id=1" << endl;
v = db->getServicesForClient(1);
for (vector<shared_ptr<netspy::db::Service> >::const_iterator iter = v->begin(); iter != v->end(); ++iter) {
cout << (*iter)->id << ": " << (*iter)->description << endl;
}
//test possible replies
cout << "getting possible replies" << endl;
boost::shared_ptr<const vector<shared_ptr<netspy::db::Reply> > > r = db->getReplies();
for (vector<shared_ptr<netspy::db::Reply> >::const_iterator iter = r->begin(); iter != r->end(); ++iter) {
cout << (*iter)->id << ", " << (*iter)->message << endl;
}
}
int main(int argc, char** argv) {
string newIP("123.143.111");
string newHash("46FBYN");
unsigned short newPort(70);
string newRemark("a test driver");
shared_ptr <DataProxy> db = DataProxy::getInstance();
// DODANIE NOWEGO KOMPUTERA
unsigned int newId = db->addClient(newIP,newPort,newHash,newRemark);
// WERYFIKACJA
unsigned int newId2 = db->addClient(newIP,newPort,newHash,newRemark);
cout<<"Duplicate clients test: ";
assert(newId == newId2);
cout<<"OK"<<endl;
//DODANIE NOWEJ USŁUGI I WERYFIKACJA POPRAWNOŚĆI DZIAŁANIA FUNKCJI PRZY PRÓBIE PONOWNEGO DODANIA
int sid = db->addService(string("test"));
int sid2 = db->addService(string("test"));
cout<<"Service creation test: ";
assert(sid==sid2);
cout<<"OK"<<endl;
//WERYFIKACJA PRZYPISANYCH USŁUG
cout<<"Assigned services test (by id): ";
assert((db->getServicesForClient(newId)->size())==0);
cout<<"OK"<<endl;
cout<<"Assigned services test (by hash): ";
assert(db->getServicesForClient(newHash)->size()==0);
cout<<"OK"<<endl;
//DOPISANIE JAKICHŚ USŁUG.
db->setClientService(newId,1,true);
db->setClientService(newId,sid,true);
cout<<"Assigned services count upon set (by hash): ";
assert(db->getServicesForClient(newHash)->size()==2);
cout<<"OK"<<endl;
db->setClientService(newId,sid,false);
cout<<"Assigned services count upon disabling one (by id): ";
assert(db->getServicesForClient(newId)->size()==1);
cout<<"OK"<<endl;
db->setClientService(newHash,sid,true);
cout<<"Assigned services count upon re0enabling one (by id): ";
assert(db->getServicesForClient(newId)->size()==2);
cout<<"OK"<<endl;
cout<<"Will insert some records about services availability"<<endl;
//get the Replies
shared_ptr<const vector<shared_ptr<Reply> > > r = db->getReplies();
int alive=0, dead=0, none=0;
for (vector<shared_ptr<netspy::db::Reply> >::const_iterator iter = r->begin(); iter != r->end(); ++iter) {
if((*iter)->message.compare(string("alive"))==0){
alive=(*iter)->id;
cout<<"alive: "<<alive<<endl;
}else if((*iter)->message.compare(string("dead"))==0){
dead=(*iter)->id;
cout<<"dead: "<<dead<<endl;
}else{
none=(*iter)->id;
cout<<"none: "<<none<<endl;
}
}
for(int i=0; i<100; ++i){
if(rand()<RAND_MAX*0.75){
if(rand()>RAND_MAX*0.7){
db->addRecord(newId,(*db->getServicesForClient(newHash)->begin())->id,none);
}else{
db->addRecord(newId,(*db->getServicesForClient(newHash)->begin())->id,alive);
}
}else{
db->addRecord(newId,(*db->getServicesForClient(newHash)->begin())->id,dead);
}
sleep(1);
}
cout<<"Hit enter to delete the newly added data and proceed with tests"<<endl;
cin.ignore(1);
//USUNIĘCIE NOWO DODANEGO KLIENTA I WSZYSTKICH JEGO DANYCH
db->deleteClientsData(newId);
cout<<"Get client by id upon deletion: ";
assert(db->getClient(newId).get()==NULL);
cout<<"OK"<<endl;
cout<<"Get client by hash upon deletion: ";
assert(db->getClient(newHash).get()==NULL);
cout<<"OK"<<endl;
//WERYFIKACJA PRZYPISANYCH USŁUG
cout<<"Assigned services upon deletion test (by id): ";
assert((db->getServicesForClient(newId)->size())==0);
cout<<"OK"<<endl;
cout<<"Assigned services upon deletion test (by hash): ";
assert(db->getServicesForClient(newHash)->size()==0);
cout<<"OK"<<endl;
return 0;
}
| 11z-zpr-netspy | trunk/server/DataTest.cpp | C++ | gpl3 | 5,390 |
#include <iostream>
#include "Config.hpp"
#include "ClientRegistrar.hpp"
#include "ClientManager.hpp"
#include "RequestManager.hpp"
#include "ClientChecker.hpp"
#include "Types.hpp"
/**
* @mainpage
* @author Marcin Ciechowicz
* Main Loop for Net-Spy
*
*/
using namespace netspy;
int main(int argc, char* argv[])
{
// załadowanie domyślnej konfiguracji
Config &config = Config::getInstance();
try
{
// ew. zczytanie dodatkowego info z linii poleceń
config.parseCommandLine(argc,argv);
// singletony incjalizowane/uruchamiane w jednym wątku
// żeby uniknąć problemów z synchronizacja
ClientManager::getInstance().initialize(); // ladowanie informacji z bazy danych
RequestManager::getInstance().run(); // uruchomienie zarzadcy komunikatow
ClientRegistrar::getInstance().setPort(config.getRegisterPort());
ClientRegistrar::getInstance().run(); // uruchomienie Rejstratora Klientów
ClientChecker::getInstance().runCheckers(config.getCheckerThreadNumber()); // uruchomienie wątków sprawdzających Klientów
for(;;){} // i latamy sobie w kółko
}
catch (std::exception& e)
{
std::cerr << "What a Terrible Failure: " << e.what() << "\n";
}
catch (int) // można ładniej ale działa
{
// drukuje helpa, ale gdzie indziej :)
}
return 0;
}
| 11z-zpr-netspy | trunk/server/main.cpp | C++ | gpl3 | 1,302 |
#ifndef CONFIG_HPP
#define CONFIG_HPP
#include "Types.hpp"
#include <string>
namespace netspy
{
class Config
{
public:
static Config &getInstance()
{
static Config config;
return config;
}
void parseCommandLine(int argc, char *argv[]) throw(int);
void setDefaultValues();
bool isVerbose() const;
uint32_t getCheckPeriod() const;
uint16_t getRegisterPort() const;
const char * getDatabaseName() const;
const char * getDatabaseUser() const;
const char * getDatabasePass() const;
uint32_t getCheckerThreadNumber() const;
private:
Config();
Config(const Config &);
Config& operator=(const Config&);
uint32_t checkPeriod_;
uint16_t registerPort_;
bool isVerbose_;
const char * databaseName_;
const char * databaseUser_;
const char * databasePass_;
uint32_t checkerThreadNumber_;
static const uint32_t defaultCheckPeriod = 60; // seconds
static const uint32_t defaultCheckerThreadNumber = 10;
static const char * configFilename() { return "spynet-server.conf"; }
static const bool defaultVerbose = true;
static const uint16_t defaultRegisterPort = 5000;
static const char * defaultDatabaseName(){ return "netspy"; }
static const char * defaultDatabaseUser(){ return "root"; }
static const char * defaultDatabasePass(){ return "root"; }
};
}
#endif
| 11z-zpr-netspy | trunk/server/Config.hpp | C++ | gpl3 | 1,375 |
#ifndef SYNCHRONIZED_QUEUE_HPP
#define SYNCHORNIZED_QUEUE_HPP
#include <queue>
#include <boost/thread.hpp>
template<typename Data>
class SynchronizedQueue
{
private:
std::queue<Data> queue_;
mutable boost::mutex mutex_;
boost::condition_variable conditionVariable_;
public:
void push(Data const& data)
{
boost::mutex::scoped_lock lock(mutex_);
queue_.push(data);
lock.unlock();
conditionVariable_.notify_one();
}
bool empty() const
{
boost::mutex::scoped_lock lock(mutex_);
return queue_.empty();
}
bool tryToPop(Data& data)
{
boost::mutex::scoped_lock lock(mutex_);
if(queue_.empty())
{
return false;
}
data=queue_.front();
queue_.pop();
return true;
}
void waitAndPop(Data& data)
{
boost::mutex::scoped_lock lock(mutex_);
while(queue_.empty())
{
conditionVariable_.wait(lock);
}
data=queue_.front();
queue_.pop();
}
};
#endif
| 11z-zpr-netspy | trunk/server/SynchronizedQueue.hpp | C++ | gpl3 | 1,083 |
#ifndef __TSS_H__
#define __TSS_H__
#define TASKIDLE 0x12000
#define TASKWORMC 0x13000
#define TASKWORMD 0x14000
#define TASKMONDRIANC 0x15000
#define TASKMONDRIAND 0x16000
#define uint unsigned int
typedef struct str_tss {
unsigned short ptl;
unsigned short unused0;
unsigned int esp0;
unsigned short ss0;
unsigned short unused1;
unsigned int esp1;
unsigned short ss1;
unsigned short unused2;
unsigned int esp2;
unsigned short ss2;
unsigned short unused3;
unsigned int cr3;
unsigned int eip;
unsigned int eflags;
unsigned int eax;
unsigned int ecx;
unsigned int edx;
unsigned int ebx;
unsigned int esp;
unsigned int ebp;
unsigned int esi;
unsigned int edi;
unsigned short es;
unsigned short unused4;
unsigned short cs;
unsigned short unused5;
unsigned short ss;
unsigned short unused6;
unsigned short ds;
unsigned short unused7;
unsigned short fs;
unsigned short unused8;
unsigned short gs;
unsigned short unused9;
unsigned short ldt;
unsigned short unused10;
unsigned short dtrap;
unsigned short iomap;
} __attribute__((__packed__, aligned (8))) tss;
/** Tabla de TSSs **/
extern tss tsss[];
extern tss tarea_inicial;
extern tss tarea_idle;
extern uint TAREA_INICIAL;
void inicializar_tss_desc();
void cargar_tss_desc(uint index, tss* dir_tarea);
void cargar_tss(tss* tarea_tss, uint cr3,uint pila, uint eip);
void duplicar_tss(tss *src, tss *dest, uint cr3);
#define TSS_COUNT 10
#endif //__TSS_H__
| 022011-tp3-o2 | trunk/tp3-entregable/tss.h | C | gpl3 | 1,482 |
#ifndef __ISR_H__
#define __ISR_H__
void _isr0();
void _isr1();
void _isr2();
void _isr3();
void _isr4();
void _isr5();
void _isr6();
void _isr7();
void _isr8();
void _isr9();
void _isr10();
void _isr11();
void _isr12();
void _isr13();
void _isr14();
void _isr15();
void _isr16();
void _isr17();
void _isr18();
void _isr19();
void _isr32();
void _isr33();
void _isr66();
void _isr77();
void _isr88();
void _isr99();
#endif // __ISR_H__
| 022011-tp3-o2 | trunk/tp3-entregable/isr.h | C | gpl3 | 441 |
#include "mmu.h"
#include "i386.h"
#include "debug.h"
#define PRESENTE 1
#define RW 2
/***************************************************
* Contadores para paginas libres
*
* siempre apuntan a la ultima pagina ocupada
* los guardamos como uint y a la hora de devolverlos
* los convertimos a punteros
***************************************************/
uint contador_pagina_kernel = INICIO_PAGINAS_KERNEL-TAMANO_PAGINA;
uint contador_pagina_usuario = INICIO_PAGINAS_USUARIO - TAMANO_PAGINA;
/***************************************************
* uint pagina_libre_kernel();
*
* Devuelve la proxima pagina libre de kernel
* Si no hay mas espacio devuelve null
***************************************************/
uint* pagina_libre_kernel(){
//incremento contador
contador_pagina_kernel = contador_pagina_kernel + TAMANO_PAGINA;
//si no llegue al limite devuelvo la pagina
if (contador_pagina_kernel < FIN_PAGINAS_KERNEL)
return (uint *)contador_pagina_kernel;
else
return 0;
}
/***************************************************
* uint pagina_libre_usuario();
*
* Devuelve la proxima pagina libre de usuario
* Si no hay mas espacio devuelve null
***************************************************/
uint* pagina_libre_usuario(){
//incremento contador
contador_pagina_usuario = contador_pagina_usuario + TAMANO_PAGINA;
//si no llegue al limite devuelvo la pagina
if (contador_pagina_usuario < FIN_PAGINAS_USUARIO)
return (uint *)contador_pagina_usuario;
else
return 0;
}
void inicializar_mmu(){
lcr3((uint) inicializar_dir_usuario());
}
void inicializar_dir_kernel(){
lcr3((uint) identity_map(4096));
}
uint* inicializar_dir_usuario(){
return identity_map(2048);
}
/*************************************
* Crea una estructura de paginacion
* con identity map en la cantidad de
* Kbytes pasado como parametro
*
* PRE: cant mayor a 0 y menor a 4Mb
*************************************/
uint* identity_map(uint cant){
//Pido una pagina para guardar una PD de usuario
uint *pd = pagina_libre_kernel();
uint i;
for(i=1;i < 1024;i++){
// PD entry no presentes R/W
pd[i] = RW;
}
// Pido una pagina para guardar una PT de usuario
uint *pt = pagina_libre_kernel();
// PD entry inicial
pd[0] = (uint)pt + RW + PRESENTE;
//Identity Map de los primeros 2Mb
cant = cant / 4;
uint acum = RW + PRESENTE;
for(i=0; i < cant; i++){
// PT entry con identity map
pt[i] = acum;
acum += TAMANO_PAGINA;
}
//Vacia las otras entradas de la PT
for(i = cant; i < 1024; i++){
pt[i] = 0x0 + RW;
}
return pd;
}
void mapear_pagina(uint virtual, uint cr3, uint fisica){
//obtengo los primeros 10 bits
uint index = virtual >> 22;
//obtengo la direccion de la PD
uint *pd = (uint *)(cr3 & ~0xFFF);
//obtengo la direccion de la PT
uint *pt = (uint *)pd[index];
//Me fijo si esta presente
if((uint)pt % 2 == 1){
//~ logText("PT Presente");
pt = (uint *)((uint)pt & ~0xFFF);
}else{
//~ logText("PT NO Presente");
//Pido una pagina para guardar una PD de usuario
pt = pagina_libre_kernel();
//~ logText("index en PD");
//~ logVal(index, 16);
//agrego en el PD esta entrada
pd[index] = (uint)pt + RW + PRESENTE;
//~ logText("PT:");
//~ logVal(pd[index], 16);
uint i;
//Vacia las entradas de la PT
for(i=0; i < 1024; i++){
pt[i] = 0x0 + RW;
}
}
//me quedo con los 10 bits del medio
index = (virtual << 10) >> 22;
//Alineo 4K la direccion fisica
//indico que esta presente
//e indexo PT
pt[index] = (fisica & ~0xFFF) + RW + PRESENTE;
//~ logText("PT entry:");
//~ logVal(pt[index], 16);
//~ __asm __volatile("xchg %bx, %bx");
//reinicia cache
}
void unmapear_pagina(uint virtual, uint cr3){
uint *p = buscar_entrada(virtual, cr3);
if((uint)p != 0){
//borro la entrada
p[0] = 0x0 + RW;
//reinicia cache
tlbflush();
}
}
uint* buscar_entrada(uint virtual, uint cr3){
//obtengo los primeros 10 bits
uint index = virtual >> 22;
//obtengo la direccion de la PD
uint *pd = (uint *)(cr3 & ~0xFFF);
//obtengo la direccion de la PT
uint *pt = (uint *)pd[index];
//Si esta presente, borro la entrada
if((uint)pt % 2 == 1){
//~ logText("PT Presente");
pt = (uint *)((uint)pt & ~0xFFF);
//me quedo con los 10 bits del medio
index = (virtual << 10) >> 22;
//borro la entrada
return &(pt[index]);
}
return (uint *)0;
}
void copiar_pagina(uint source, uint dest){
//guardo la entrada, si existe, en el cr3 actual
uint *p_dest = buscar_entrada(dest, rcr3());
uint dest_antiguo = p_dest[0];
uint *p_src = buscar_entrada(source, rcr3());
uint src_antiguo = p_src[0];
mapear_pagina(source, rcr3(), source);
mapear_pagina(dest, rcr3(), dest);
uint i=0;
for(; i < 1024; i++){
((uint*)dest)[i]=((uint*)source)[i];
}
p_src[0] = src_antiguo;
p_dest[0] = dest_antiguo;
}
| 022011-tp3-o2 | trunk/tp3-entregable/mmu.c | C | gpl3 | 5,567 |
#include "pic.h"
#define PIC1_PORT 0x20
#define PIC2_PORT 0xA0
static __inline __attribute__((always_inline)) void outb(int port, unsigned char data) {
__asm __volatile("outb %0,%w1" : : "a" (data), "d" (port));
}
__inline __attribute__((always_inline)) void fin_intr_pic1(void) { outb(0x20, 0x20); }
__inline __attribute__((always_inline)) void fin_intr_pic2(void) { outb(0x20, 0x20); outb(0xA0, 0x20); }
void resetear_pic() {
outb(PIC1_PORT+0, 0x11); /* IRQs activas x flanco, cascada, y ICW4 */
outb(PIC1_PORT+1, 0x20); /* Addr */
outb(PIC1_PORT+1, 0x04); /* PIC1 Master, Slave ingresa Int.x IRQ2 */
outb(PIC1_PORT+1, 0x01); /* Modo 8086 */
outb(PIC1_PORT+1, 0xFF); /* Enmasca todas! */
outb(PIC2_PORT+0, 0x11); /* IRQs activas x flanco, cascada, y ICW4 */
outb(PIC2_PORT+1, 0x28); /* Addr */
outb(PIC2_PORT+1, 0x02); /* PIC2 Slave, ingresa Int x IRQ2 */
outb(PIC2_PORT+1, 0x01); /* Modo 8086 */
outb(PIC2_PORT+1, 0xFF); /* Enmasca todas! */
}
void habilitar_pic() {
outb(PIC1_PORT+1, 0x00);
outb(PIC2_PORT+1, 0x00);
}
void deshabilitar_pic() {
outb(PIC1_PORT+1, 0xFF);
outb(PIC2_PORT+1, 0xFF);
}
| 022011-tp3-o2 | trunk/tp3-entregable/pic.c | C | gpl3 | 1,126 |
BITS 32
push eax
; pide el pid para mostrarlo como caracter del gusano
int 88
add eax, 0x30
mov byte [ebp-0x1e], al
int 88
; color aleatorio para el fondo
shl al, 4
add al, 0xF
mov byte [ebp-0x5a], al
; inicio aleatorio del gusano
and eax, 0xF0
add eax, 0x50
add eax, 0xB8000
mov dword [ebp-0x14], eax
;~ xchg bx, bx
pop eax
ret
| 022011-tp3-o2 | trunk/tp3-entregable/hack.asm | Assembly | gpl3 | 333 |
#ifndef __GDT_H__
#define __GDT_H__
#define uint unsigned int
typedef struct str_gdt_descriptor {
unsigned short gdt_length;
unsigned int gdt_addr;
} __attribute__((__packed__)) gdt_descriptor;
typedef struct str_gdt_entry {
unsigned short limit_0_15;
unsigned short base_0_15;
unsigned char base_23_16;
unsigned char type:4;
unsigned char s:1;
unsigned char dpl:2;
unsigned char p:1;
unsigned char limit_16_19:4;
unsigned char avl:1;
unsigned char l:1;
unsigned char db:1;
unsigned char g:1;
unsigned char base_31_24;
} __attribute__((__packed__, aligned (8))) gdt_entry;
/** Tabla GDT **/
extern gdt_entry gdt[];
extern gdt_descriptor GDT_DESC;
#define GDT_COUNT 128
#endif //__GDT_H__
| 022011-tp3-o2 | trunk/tp3-entregable/gdt.h | C | gpl3 | 709 |
#include "isr.h"
#include "idt.h"
#include "i386.h"
#define IDT_ENTRY(numero) \
idt[numero].offset_0_15 = (unsigned short) ((unsigned int)(&_isr ## numero) & (unsigned int) 0xFFFF); \
idt[numero].segsel = (unsigned short) 0x0030; \
idt[numero].attr = (unsigned short) 0x8E00; \
idt[numero].offset_16_31 = (unsigned short) ((unsigned int)(&_isr ## numero) >> 16 & (unsigned int) 0xFFFF);
#define TASK_GATE_ENTRY(numero) \
idt[numero].offset_0_15 = (unsigned short) 0x0; \
idt[numero].segsel = (unsigned short) 0x0008; \
idt[numero].attr = (unsigned short) 0x8500; \
idt[numero].offset_16_31 = (unsigned short) 0x0;
void inicializar_idt() {
IDT_ENTRY(0);
IDT_ENTRY(1); //RESRVED mnemonic(#DB)
IDT_ENTRY(2); // interrupt
IDT_ENTRY(3); // breakpoint mnemonic(#BP)
IDT_ENTRY(4); // OVERFLOW MNEMONIC(#OF)
IDT_ENTRY(5); // BOUND RANGE EXCEEDED MNEMONIC(#BR)
IDT_ENTRY(6); // INVALID OPCODE MNEMONIC(#UD)
IDT_ENTRY(7); // DEVICE NOT AVAILABLE MNEMONIC(#NM)
IDT_ENTRY(8); // DOUBLE FAULT MNEMONIC(#DF)
IDT_ENTRY(9); // COPROCESSOR SEGMENT OVERRUN MNEMONIC()
IDT_ENTRY(10); // INVALID TSS MNEMONIC(#TS)
IDT_ENTRY(11); // SEGMENT NOT PRESENT MNEMONIC(#NP)
IDT_ENTRY(12); // STACK-SEGMENT FAULT MNEMONIC(#SS)
IDT_ENTRY(13); // GENERAL PROTECTION MNEMONIC(#GP)
IDT_ENTRY(14); // PAGE FAULT MNEMONIC(#PF)
IDT_ENTRY(15); // INTEL RESERVED MNEMONIC()
IDT_ENTRY(16); // FPU FLOATING POINT ERROR MNEMONIC(#MF)
IDT_ENTRY(17); // ALIGNMENT CHECK MNEMONIC(#AC)
IDT_ENTRY(18); // MACHINE CHECK MNEMONIC(#MC)
IDT_ENTRY(19); // SIMD FLOATING POINT EXCEPTION MNEMONIC(#XF)
IDT_ENTRY(32); // CLOCK
IDT_ENTRY(33); // TECLADO
//~ IDT_ENTRY(66); // FORK
TASK_GATE_ENTRY(66); // FORK
IDT_ENTRY(77); //
IDT_ENTRY(88); //
IDT_ENTRY(99); //
}
idt_entry idt[255] = {};
idt_descriptor IDT_DESC = {sizeof(idt)-1, (unsigned int)&idt};
| 022011-tp3-o2 | trunk/tp3-entregable/idt.c | C | gpl3 | 1,880 |