Postgresql passwordcheck.c modification - c

I need to modify the https://github.com/postgres/postgres/blob/REL9_5_13/contrib/passwordcheck/passwordcheck.c in order to check the password before set it.
I'm not very good with C.
So I added this check:
if (validuntil_null)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("password expiriration missing")));
and it works, it checks if the expiration date is set.
Now I want to check if this expiration date is reasonable, like no more than 3 months (using "validuntil_time") and if it is different from the previous set.
Any idea?
thanks in advance.

I am not familiar with the internals of PostgreSQL or the configuration of PostgreSQL. My first approach would be to study the documentation to determine if it is possible to set a maximum password expiration time using the admin privileges. I am guessing that you have studied that in detail already and feel that this is the best option.
Based on that, I did review some of the timestamp code in the Postgres github repository. I have not compiled this, but believe this is close. It was not clear to me what Datum is, whether that is already a TimeStampTz type, or if that needs to be converted in some way. It might not compile properly without answering that question. Let me know if this works for you:
At the top of the file, add this to the includes:
#include "utils/timestamp.h"
Later, at the same place where you placed your current code, replace your code with this:
if (validuntil_null) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("password expiriration missing")));
} else {
TimestampTz now = GetCurrentTimestamp();
const int ThreeMonthsInMiliSeconds = 90 * 24 * 3600 * 1000;
if(TimestampDifferenceExceeds(now, validuntil_time, ThreeMonthsInMiliSeconds) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("password expiriration time is greater than 90 days")));
}
}
Here is the source code for that timedifference function from timestamp.c:
/*
* TimestampDifferenceExceeds -- report whether the difference between two
* timestamps is >= a threshold (expressed in milliseconds)
*
* Both inputs must be ordinary finite timestamps (in current usage,
* they'll be results from GetCurrentTimestamp()).
*/
bool
TimestampDifferenceExceeds(TimestampTz start_time,
TimestampTz stop_time,
int msec)
{
TimestampTz diff = stop_time - start_time;
return (diff >= msec * INT64CONST(1000));
}

Thanks John, at the end I managed in that way:
if (validuntil_null) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("password expiriration missing")));
} else {
TimestampTz now = GetCurrentTimestamp();
const off64_t threshold = (const off64_t)((off64_t)90 * 24 * 3600 * 1000 );
if (now > validuntil_time) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("\nERROR now: %ld validuntil_time: %ld threshold: %ld",now,validuntil_time,threshold)));
} else {
const off64_t diff= (const off64_t)((off64_t)(validuntil_time - now)/1000);
if (diff >= threshold) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("\nERROR: DATE is more than 90 days: now: %ld validuntil_time: %ld threshold: %ld",now,validuntil_time,threshold)));
}
elog(INFO,"\nnow: %ld validuntil_time: %ld threshold: %ld diff: %ld",now,validuntil_time,threshold,diff);
}
}
Thanks

Related

How to make code run every X seconds in C programming language

I am trying to make a code run repeatedly every X seconds.
Let me paint a wrestling scenario.
I have already written a code line to give Tyson fury a 5Kg punch at 40 seconds into the fight and then stop.. but there's no way I'm going to win the match with just one 5kg punch at 40 seconds. I need to be able to keep punching every 40 seconds.
Please who knows how I can achieve this?
PS.
{
real punch;
real time = CURRENT_TIME;
real tau = 40;
if (time<=tau)
{
punch=5;
}
else
{
punch=0;
}
return punch;
}
In a scenario where time acquisition is possible, as I can see you use
CURRENT_TIME
You can do it like this:
static int lastTimeExecuted = 0; // Using int here, but you should mach type of CURRENT_TIME
// See how much time passed since last execution
if ((CURRENT_TIME - lastTimeExecuted) >= 40)
{
punch = 5;
lastTimeExecuted = CURRENT_TIME ;
}
else
{
punch = 0;
}
Just remember that code abowe shuld be in a loop.

Cannot get MT4 indicator to work using prebuilt library

I'm using the code from this article https://www.mql5.com/en/articles/159 to calculate when a new bar opens but it's not displaying the historical data for the indicator.
I have modified the TimeCurrent() to iTime( _Symbol, _Period, shift ) so as to try to handle this, but it's not working.
Could you tell me what I'm doing wrong please?
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 RoyalBlue
#include <Lib_CisNewBar.mqh>
CisNewBar current_chart;
//---- input parameters
extern int Length=18; // Bollinger Bands Period
extern int Deviation=2; // Deviation was 2
extern double MoneyRisk=1.00; // Offset Factor
extern int Signal=1; // Display signals mode: 1-Signals & Stops; 0-only Stops; 2-only Signals;
extern int Line=1; // Display line mode: 0-no,1-yes
extern int Nbars=1000;
//---- indicator buffers
double TrendBuffer[];
extern bool SoundON=true;
bool TurnedUp = false;
bool TurnedDown = false;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
string short_name;
//---- indicator line
SetIndexBuffer(0,TrendBuffer);
SetIndexStyle(0,DRAW_LINE,0,1);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS));
short_name="Example ("+Length+","+Deviation+")";
IndicatorShortName(short_name);
SetIndexLabel(0,"Trend Value");
//----
SetIndexDrawBegin(0,Length);
//----
return(INIT_SUCCEEDED);
}
void deinit()
{
}
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
int shift;
for (shift=Nbars;shift>=0;shift--)
{
TrendBuffer[shift]=0;
}
for (shift=Nbars-Length-1;shift>=0;shift--)
{
int period_seconds=PeriodSeconds(_Period);
datetime new_time=iTime(_Symbol,_Period,shift)/period_seconds*period_seconds;
if(current_chart.isNewBar(new_time))
{
Print("time[shift] = "+TimeToString(time[shift]));
if( Close[shift] > Close[shift+1] )
TrendBuffer[shift]=1;
else if(Close[shift] < Close[shift+1] )
TrendBuffer[shift]=-1;
else
TrendBuffer[shift]=0;
}
}
return(0);
}
Thanks.
a) The "new"-MQL4.56789 has another syntax
For Custom Indicator, the "new"-MQL4.56789 source shall rather read
void OnInit(){ ... }andvoid OnDeinit( const int anMT4_Reason2callDeinit ){ ... }
b) The datetime
Your code defines a variable new_time, typed as a datetime
The datetime type is intended for storing the date and time as the number of seconds elapsed since January 01, 1970.
and
Values range from 1 January, 1970 to 31 December, 3000
So, in case of your new_time assignment, the proper iTime() value is divided by an amount of PeriodSeconds() and right next it is re-multiplied by the exact same value, which should not change the value of the iTime() result.
Such operation, while having no theoretical impact on result, might in practice of a code-execution introduce a risk of a numerical inaccuracy, range overflow/underflow and a theoretical notice about a resolution of an 8-byte class storage is not helping to go past the upper bound limit, stated in the documentation as Dec-31, 3000.
In similar cases unpredicatable results and even MT4 unhandled exceptions and MQL4-code terminations are to be expected.
What worse one may expect for a production grade software? So, avoid, avoid and avoid any such risk.
There is no direct positive value for such a Custom Indicator calculation step.
c) TimeCurrent() / PeriodSeconds() side-effect of rounding
While iTime() is always divisible by it's "own" time-frame PeriodSeconds(), TimeCurrent() is not.
Thus one may read the original ( assumed ) construct of
TimeCurrent() / PeriodSeconds() // .DIV is subject to rounding to int
* PeriodSeconds(); // before the forthcoming .MUL
"hacks" the need to align a [last known server time, time of the last quote receipt for one of the symbols selected in the "Market Watch" window] to one's "own" time-frame value of a start-of-current bar time.
d) The article is from 11 October 2010 (!) - be very carefull in MQL4
Current MQL4 code-execution engine is Build 890 ( 25 Sep 2015 ), so your cited source was using an MQL5 language syntax some 5 years old (!!), which namely in MQL4-domain means _be_very_carefull_
In the meantime string-s ceased to be string-s,
many GUI functions have several calling protocols in parallel,
andcountless man*years of DLL/API-code-base dev/maint were lost due to similar moving sands.
So -5- years gap is a warning per-se.
One never enters the same river twice
The recent state of "new"-MQL4.56789 allows a clean approach:
in case your motivation is just to be able to detect on-demand a situation a new bar has started, the Build-890/1174 compiler allows for a cleaner approach:
bool aNewBarEVENT( const string anFxSYMBOL, // _Symbol,
const int aTimeFRAME // PERIOD_M6
)
{ static int pBars = EMPTY; // previous
int oBars = iBars( anFxSYMBOL, aTimeFRAME ); // observed
if ( pBars == oBars ) return( False ); // .NACK
pBars = oBars, return( True ); // .UPD + .ACK
}

How to create a Bank Calendar with 30 days each month

For calculating annuity loan with german I need a calendar where every month has exactly 30 days. Every year has 360 days. There are no leap years.
The interest is allways calculated on a basis of 30 day (That's the german interest method)
I'm using Java 8. What possibilities do I have with the new java.time API to accomplish my requirements?
What you describe is a day count not a calendar system. A day count is a mechanism for converting the period between two dates into a year fraction.
Strata from OpenGamma includes implementations of many day counts, including 30E/360 which may be the method you need.
With Java-8 there are in principle two options for implementing any calendar:
Using the interfaces ChronoLocalDate and Chronology as starting point
Using the interface Temporal
In my honest opinion, both options are a no-go in your use case. The first option using the java.time.chrono-package forces you to bother with era, year-of-era etc. which is not relevant at all for 360-day-calendars. The second option is too abstract and simple to offer any surplus value compared with just implementing your calendar from the scratch.
A first starting point would be to study the literature and internet, for example in extreme short Wikipedia. It is also important to recognize and take into your design considerations that such a 360-day-"calendar" is not a calendar in strict sense because it does not define a unique and bijective mapping from the calendar date to julian days (several equal dates might belong to different real days! - another important reason to reject the use of chrono-package). The practical consequence would be only to define conversion/factory methods like
Financial360DayCalendar f360 = Financial360DayCalendar.of(LocalDate date);
but not the reverse direction. Beyond the question of mapping/conversion, the calculation of the duration in days between two such dates is the main issue in this "calendar". If you solve both aspects then your task is done. More stuff is probably not needed unless you need formatting. For formatting purposes, you might consider implementing the Java-8-interface TemporalAccessor.
An (incomplete) idea:
class Financial360DayCalendar {
private final int year;
private final int month;
private final int dayOfMonth;
private Financial360DayCalendar(int year, int month, int dayOfMonth) {
this.year = year;
this.month = month;
this.dayOfMonth = dayOfMonth;
}
public static Financial360DayCalendar of(LocalDate date) {
int year = date.getYear();
int month = date.getMonthValue();
int dayOfMonth = date.getDayOfMonth();
if (dayOfMonth == 31) {
dayOfMonth = 30;
}
return new Financial360DayCalendar(year, month, dayOfMonth);
}
public int durationInDaysUntil(Financial360DayCalendar other) {
// check also if other is not before this instance
// ...
// special algorithm (handling all intervening months as 30 days long)
int interestDays = 30 - this.dayOfMonth(); // current day excluded
int monthDelta = other.getMonthCount() - this.getMonthCount();
if (monthDelta > 0) {
monthDelta--;
}
interestDays += (30 * monthDelta + other.dayOfMonth);
return interestDays;
}
public double getYearFraction(Financial360DayCalendar other) {
return durationInDaysUntil(other) / 360.0;
}
private int getMonthCount() {
return this.year * 12 + this.month;
}
}
So it is rather a method for calculating interests, not a real calendar system. You can also refer to this website (in German) to see the details how to calculate the duration.
You should use standard calendar, there is no need to make a custom one. If you need to calculate a days between two dates based on 30 days month, use something like this method:
public int calculateDays(Date d1, Date d2) {
int months = 0;
int days = 0;
months = Months.monthsBetween(new DateTime(d1), new DateTime(d2)).getMonths();
int endOfMonth = d1.getDate() == 31 ? 31 : 30;
if(d1.getDate() > d2.getDate()){
days = endOfMonth - d1.getDate() + d2.getDate();
}else{
days = d2.getDate() - d1.getDate();
}
months = months * 30;
days = months + days;
return days;
}
I used JodaTime to simplify implementation.

Low Pass filter in C

I'm implementing a low pass filter in C wih the PortAudio library.
I record my microphone input with a script from PortAudio itself. There I added the following code:
float cutoff = 4000.0;
float filter(float cutofFreq){
float RC = 1.0/(cutofFreq * 2 * M_PI);
float dt = 1.0/SAMPLE_RATE;
float alpha = dt/(RC+dt);
return alpha;
}
float filteredArray[numSamples];
filteredArray[0] = data.recordedSamples[0];
for(i=1; i<numSamples; i++){
if(i%SAMPLE_RATE == 0){
cutoff = cutoff - 400;
}
data.recordedSamples[i] = data.recordedSamples[i-1] + (filter(cutoff)*(data.recordedSamples[i] - data.recordedSamples[i-1]));
}
When I run this script for 5 seconds it works. But when I try to run this for more then 5 seconds it fails. The application records everything, but crashes on playback. If I remove the filter, the application works.
Any advice?
The problem:
you are lowering the cutoff frequency by 400 Hz everytime i%SAMPLE_RATE == 0
never stop so you go below zero
this is not done once per second !!!
instead every time your for passes through second barrier in your data
that can occur more often then you think if you are not calling your calls in the right place
which is not seen in your code
you are filtering in wrong oorder
... a[i]=f(a[i],a[i-1]; i++;
that means you are filtering with already filtered a[i-1] value
What to do with it
check the code placement
it should be in some event like on packed done sompling
or in thread after some Sleep(...); (or inside timer)
change the cut off changing (handle edge cases)
reverse filter for direction
Something like this:
int i_done=0;
void on_some_timer()
{
cutoff-=400;
if (cutoff<1) cutoff=1; // here change 1 for limit frequency
if (numSamples!=i_done)
for (i=numSamples-1,i>=i_done;i--)
data.recordedSamples[i] = data.recordedSamples[i-1] + (filter(cutoff)*(data.recordedSamples[i] - data.recordedSamples[i-1]));
i_done=numSamples;
}
if your code is already OK (you did not post th whole thing so I can missing something)
then just add the if (cutoff<1) cutoff=1; after cutoff change

How to implement a C function that will not proceed with it's operations if it is called more than 100 times per second?

I need to implement a function which should not proceed it's operations if it is called more than 100 times per a sec. Any suggestions how can I write this function in C?
How about:
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
uint64_t timedfun(uint64_t a, uint64_t b) //dummy arguments, replace with yours
{
static time_t lastt; //might want to use _Thread_local
static uint_fast8_t count; //might want to use _Thread_local
time_t currt = time(NULL);
if (lastt != currt)
{
lastt = currt;
count = 0;
}
if (++count > 100)
{
exit(EXIT_FAILURE); //You didn't specify what to do when it's called more than 100 times...
}
return a+b; //dummy result, replace with your function
}
As nos touched upon thread-safety in his answer, I've added some comments. The comments show where an applicable storage/lifetime specifier should go to ensure thread-safety (this will allow up to 100 calls to this function per thread). Otherwise this limit would be shared over all threads, and prone to race-conditions. In that case, you might need a mutex too.
Edit for non-POSIX systems, pure C-compliance (kudos to chux's comment):
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
uint64_t timedfun(uint64_t a, uint64_t b) //dummy arguments, replace with yours
{
static time_t lastt; //might want to use _Thread_local
static uint_fast8_t count; //might want to use _Thread_local
time_t currt = time(NULL);
if (difftime(lastt, currt) >= 1.0) //uses floating-point numbers, use for non-POSIX systems
{
lastt = currt;
count = 0;
}
if (++count > 100)
{
exit(EXIT_FAILURE); //You didn't specify what to do when it's called more than 100 times...
}
return a+b; //dummy result, replace with your function
}
Add:
usleep(10000);
:)
Short of that you'll need to allocate storage to hold the times of the last 100 invocations, and keep track of those in a rotating fashion. This seems silly, but perhaps there might in some dark corner of the universe be a reasonable reason to do this.
You can use a token bucket principle to rate limit your function.
First some common stuff:
struct RateLimit {
//how many tickets we want
long tickets;
//per this period of time
long period;
//internal fields:
//money we have to "buy" tickets
long funds;
//time of the previos period
long last_refill_ts;
};
#define RATELIMIT_INITIALIZER(tickets, period)\
{ tickets, period, 0, -period}
//current_ts must be in the unit of r->period
static void ratelimit_refill(struct RateLimit *r, long current_ts)
{
long diff_period;
//Find elapsed time
diff_period = current_ts - r->last_refill_ts;
if (diff_period > r->period) {
//help prevent overflow when calculating available tickets below
diff_period = r->period;
} else if (diff_period < 0) {
//time went backwards, skip this round
diff_period = 0;
}
//Calculate the cost of tickets that became available
r->funds += diff_period * r->tickets;
//throttle handing out tickets
if (r->funds > r->period * r->tickets) {
r->funds = r->period * r->tickets;
}
//save this period.
r->last_refill_ts = current_ts;
}
int ratelimit_allow(struct RateLimit *r, long current_ts)
{
int allowed;
if (r->funds < r->period) { //not enough funds
ratelimit_refill(r, current_ts);
//as we keep track of the last timestamp of refilling
//We don't need to refill when there is enough funds
}
//If we have enough to buy atleast one ticket, we can allow
if (r->funds >= r->period) {
r->funds -= r->period;
allowed = 1;
} else {
//not enough to buy a ticket
allowed = 0;
}
return allowed;
}
Then you'd use this in your function that you want to rate limit:
void my_function(void)
{ //limit to 100/sec
static struct RateLimit rl = RATELIMIT_INITIALIZER(100, 1);
if (!ratelimit_allow(&rl, time(NULL))) {
abort(); //or less drastic measures
}
//your actual code here
}
Note - this function is not thread safe, you'd have to provide a mutex or similar around the ratelimit_allow() to make it thread safe too.

Resources