Changeset 710


Ignore:
Timestamp:
28/07/2006 00:18:35 (6 years ago)
Author:
chris
Message:
  • merge
  • This is my current patch queue. I think that all of these are safe to apply. This is just under half of the pending changes in chris/general (the easy half).
Location:
box/chris/merge
Files:
3 deleted
57 edited
1 copied

Legend:

Unmodified
Added
Removed
  • box/chris/merge/bin/bbackupctl/bbackupctl.cpp

    r456 r710  
    3333        printf("Usage: bbackupctl [-q] [-c config_file] <command>\n" 
    3434        "Commands are:\n" 
    35         "  sync -- start a syncronisation run now\n" 
    36         "  force-sync -- force the start of a syncronisation run, " 
     35        "  sync -- start a synchronisation (backup) run now\n" 
     36        "  force-sync -- force the start of a synchronisation run, " 
    3737        "even if SyncAllowScript says no\n" 
    3838        "  reload -- reload daemon configuration\n" 
    3939        "  terminate -- terminate daemon now\n" 
    4040        "  wait-for-sync -- wait until the next sync starts, then exit\n" 
     41        "  wait-for-end  -- wait until the next sync finishes, then exit\n" 
     42        "  sync-and-wait -- start sync, wait until it finishes, then exit\n" 
    4143        ); 
    4244        exit(1); 
     
    108110        if(!conf.KeyExists("CommandSocket")) 
    109111        { 
    110                 printf("Daemon isn't using a control socket, could not execute command.\nAdd a CommandSocket declaration to the bbackupd.conf file.\n"); 
     112                printf("Daemon isn't using a control socket, " 
     113                        "could not execute command.\n" 
     114                        "Add a CommandSocket declaration to the " 
     115                        "bbackupd.conf file.\n"); 
    111116                return 1; 
    112117        } 
     
    189194        if(!quiet) 
    190195        { 
    191                 printf("Daemon configuration summary:\n"        \ 
    192                            "  AutomaticBackup = %s\n"                   \ 
    193                            "  UpdateStoreInterval = %d seconds\n"       \ 
    194                            "  MinimumFileAge = %d seconds\n"    \ 
    195                            "  MaxUploadWait = %d seconds\n", 
    196                            autoBackup?"true":"false", updateStoreInterval, minimumFileAge, maxUploadWait); 
     196                printf("Daemon configuration summary:\n" 
     197                        "  AutomaticBackup = %s\n" 
     198                        "  UpdateStoreInterval = %d seconds\n" 
     199                        "  MinimumFileAge = %d seconds\n" 
     200                        "  MaxUploadWait = %d seconds\n", 
     201                        autoBackup?"true":"false", updateStoreInterval,  
     202                        minimumFileAge, maxUploadWait); 
     203        } 
     204 
     205        std::string stateLine; 
     206        if(!getLine.GetLine(stateLine) || getLine.IsEOF()) 
     207        { 
     208#if defined WIN32 && ! defined NDEBUG 
     209                syslog(LOG_ERR, "Failed to receive state line from daemon"); 
     210#else 
     211                printf("Failed to receive state line from daemon\n"); 
     212#endif 
     213                return 1; 
     214        } 
     215 
     216        // Decode it 
     217        int currentState; 
     218        if(::sscanf(stateLine.c_str(), "state %d", &currentState) != 1) 
     219        { 
     220                printf("State line didn't decode\n"); 
     221                return 1; 
    197222        } 
    198223 
    199224        // Is the command the "wait for sync to start" command? 
    200225        bool areWaitingForSync = false; 
    201         if(::strcmp(argv[0], "wait-for-sync") == 0) 
    202         { 
    203                 // Check that it's not in non-automatic mode, because then it'll never start 
     226        bool areWaitingForSyncEnd = false; 
     227 
     228        if(::strcmp(argv[0], "wait-for-sync") == 0 || 
     229           ::strcmp(argv[0], "wait-for-end") == 0) 
     230        { 
     231                // Check that it's not in non-automatic mode,  
     232                // because then it'll never start 
    204233                if(!autoBackup) 
    205234                { 
    206                         printf("ERROR: Daemon is not in automatic mode -- sync will never start!\n"); 
     235                        printf("ERROR: Daemon is not in automatic mode -- " 
     236                                "sync will never start!\n"); 
    207237                        return 1; 
    208238                } 
    209239         
    210                 // Yes... set the flag so we know what we're waiting for a sync to start 
    211                 areWaitingForSync = true; 
     240                // Yes... set the flag so we know that  
     241                // we're waiting for a sync to start/end 
     242                if(::strcmp(argv[0], "wait-for-sync") == 0) 
     243                { 
     244                        areWaitingForSync = true; 
     245                } 
     246                else if (::strcmp(argv[0], "wait-for-end") == 0) 
     247                { 
     248                        areWaitingForSyncEnd = true; 
     249                } 
     250        } 
     251        else if (::strcmp(argv[0], "sync-and-wait") == 0) 
     252        { 
     253                // send a sync command 
     254                std::string cmd("force-sync\n"); 
     255                connection.Write(cmd.c_str(), cmd.size()); 
     256                connection.WriteAllBuffered(); 
     257                areWaitingForSyncEnd = true; 
     258 
     259                if (currentState != 0) 
     260                { 
     261                        printf("Waiting for current sync/error state " 
     262                                "to finish...\n"); 
     263                } 
    212264        } 
    213265        else 
     
    221273        // Read the response 
    222274        std::string line; 
     275        bool syncIsRunning = false; 
     276 
    223277        while(!getLine.IsEOF() && getLine.GetLine(line)) 
    224278        { 
     
    235289                        }                
    236290                } 
     291                else if(areWaitingForSyncEnd) 
     292                { 
     293                        if(line == "start-sync") 
     294                        { 
     295                                if (!quiet) printf("Sync started...\n"); 
     296                                syncIsRunning = true; 
     297                        } 
     298                        else if(line == "finish-sync" && syncIsRunning) 
     299                        { 
     300                                if (!quiet) printf("Sync finished.\n"); 
     301                                // Send a quit command to finish nicely 
     302                                connection.Write("quit\n", 5); 
     303                                 
     304                                // And we're done 
     305                                break; 
     306                        } 
     307                        else if(line == "finish-sync") 
     308                        { 
     309                                if (!quiet) printf("Previous sync finished.\n"); 
     310                        } 
     311                        // daemon must still be busy 
     312                } 
    237313                else 
    238314                { 
  • box/chris/merge/bin/bbackupd/BackupClientContext.cpp

    r456 r710  
    177177                        mStorageLimitExceeded = true; 
    178178                        // Log 
    179                         ::syslog(LOG_INFO, "Exceeded storage limits on server -- not uploading changes to files"); 
     179                        ::syslog(LOG_WARNING, "Exceeded storage limits on server -- not uploading changes to files"); 
    180180                } 
    181181        } 
  • box/chris/merge/bin/bbackupd/BackupClientDirectoryRecord.cpp

    r456 r710  
    646646                // 
    647647                // Condition for upload: 
    648                 //    modifiction time within sync period 
     648                //    modification time within sync period 
    649649                //    if it's been seen before but not uploaded, is the time from this first sight longer than the MaxUploadWait 
    650650                //        and if we know about it from a directory listing, that it hasn't got the same upload time as on the store 
    651                 if( 
    652                         ( 
    653                                 // Check the file modified within the acceptable time period we're checking 
    654                                 // If the file isn't on the server, the acceptable time starts at zero. 
    655                                 // Check pDirOnStore and en, because if we didn't download a directory listing, 
    656                                 // pDirOnStore will be zero, but we know it's on the server. 
    657                                 ( ((pDirOnStore != 0 && en == 0) || (modTime >= rParams.mSyncPeriodStart)) && modTime < rParams.mSyncPeriodEnd) 
    658  
    659                                 // However, just in case things are continually modified, we check the first seen time. 
    660                                 // The two compares of syncPeriodEnd and pendingFirstSeenTime are because the values are unsigned. 
    661                                 || (pendingFirstSeenTime != 0 && 
    662                                         (rParams.mSyncPeriodEnd > pendingFirstSeenTime) 
    663                                                 && ((rParams.mSyncPeriodEnd - pendingFirstSeenTime) > rParams.mMaxUploadWait)) 
    664  
    665                                 // Then make sure that if files are added with a time less than the sync period start 
    666                                 // (which can easily happen on file server), it gets uploaded. The directory contents checksum 
    667                                 // will pick up the fact it has been added, so the store listing will be available when this happens. 
    668                                 || ((modTime <= rParams.mSyncPeriodStart) && (en != 0) && (en->GetModificationTime() != modTime)) 
    669                                  
    670                                 // And just to catch really badly off clocks in the future for file server clients, 
    671                                 // just upload the file if it's madly in the future. 
    672                                 || (modTime > rParams.mUploadAfterThisTimeInTheFuture) 
    673                         )                        
    674                         // But even then, only upload it if the mod time locally is different to that on the server. 
    675                         && (en == 0 || en->GetModificationTime() != modTime)) 
     651 
     652                bool doUpload = false; 
     653 
     654                // Only upload a file if the mod time locally is  
     655                // different to that on the server. 
     656 
     657                if (en == 0 || en->GetModificationTime() != modTime) 
     658                { 
     659                        // Check the file modified within the acceptable time period we're checking 
     660                        // If the file isn't on the server, the acceptable time starts at zero. 
     661                        // Check pDirOnStore and en, because if we didn't download a directory listing, 
     662                        // pDirOnStore will be zero, but we know it's on the server. 
     663                        if (modTime < rParams.mSyncPeriodEnd) 
     664                        { 
     665                                if (pDirOnStore != 0 && en == 0) 
     666                                { 
     667                                        doUpload = true; 
     668                                } 
     669                                else if (modTime >= rParams.mSyncPeriodStart) 
     670                                { 
     671                                        doUpload = true; 
     672                                } 
     673                        } 
     674 
     675                        // However, just in case things are continually  
     676                        // modified, we check the first seen time. 
     677                        // The two compares of syncPeriodEnd and  
     678                        // pendingFirstSeenTime are because the values  
     679                        // are unsigned. 
     680 
     681                        if (!doUpload &&  
     682                                pendingFirstSeenTime != 0 && 
     683                                rParams.mSyncPeriodEnd > pendingFirstSeenTime && 
     684                                (rParams.mSyncPeriodEnd - pendingFirstSeenTime)  
     685                                > rParams.mMaxUploadWait) 
     686                        { 
     687                                doUpload = true; 
     688                        } 
     689 
     690                        // Then make sure that if files are added with a  
     691                        // time less than the sync period start 
     692                        // (which can easily happen on file server), it  
     693                        // gets uploaded. The directory contents checksum 
     694                        // will pick up the fact it has been added, so the  
     695                        // store listing will be available when this happens. 
     696 
     697                        if (!doUpload && 
     698                                modTime <= rParams.mSyncPeriodStart &&  
     699                                en != 0 &&  
     700                                en->GetModificationTime() != modTime) 
     701                        { 
     702                                doUpload = true; 
     703                        } 
     704 
     705                        // And just to catch really badly off clocks in  
     706                        // the future for file server clients, 
     707                        // just upload the file if it's madly in the future. 
     708 
     709                        if (!doUpload && modTime >  
     710                                rParams.mUploadAfterThisTimeInTheFuture) 
     711                        { 
     712                                doUpload = true; 
     713                        } 
     714                } 
     715 
     716                if (doUpload) 
    676717                { 
    677718                        // Make sure we're connected -- must connect here so we know whether 
     
    10231064                                        mSubDirectories.erase(e); 
    10241065                                        delete rec; 
    1025                                         TRACE2("Deleted directory record for %s/%s\n", rLocalPath.c_str(), dirname.GetClearFilename().c_str()); 
     1066                                        TRACE2("Deleted directory record for " 
     1067                                                "%s" DIRECTORY_SEPARATOR "%s\n", 
     1068                                                rLocalPath.c_str(),  
     1069                                                dirname.GetClearFilename().c_str()); 
    10261070                                }                                
    10271071                        } 
  • box/chris/merge/bin/bbackupd/BackupDaemon.cpp

    r547 r710  
    126126 
    127127#ifdef WIN32 
     128        // Create the event object to signal from main thread to worker 
     129        // when new messages are queued to be sent to the command socket. 
     130        mhMessageToSendEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
     131        if (mhMessageToSendEvent == INVALID_HANDLE_VALUE) 
     132        { 
     133                syslog(LOG_ERR, "Failed to create event object: error %d", 
     134                        GetLastError); 
     135                exit(1); 
     136        } 
     137 
     138        // Create the event object to signal from worker to main thread 
     139        // when a command has been received on the command socket. 
     140        mhCommandReceivedEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
     141        if (mhCommandReceivedEvent == INVALID_HANDLE_VALUE) 
     142        { 
     143                syslog(LOG_ERR, "Failed to create event object: error %d", 
     144                        GetLastError); 
     145                exit(1); 
     146        } 
     147 
     148        // Create the critical section to protect the message queue 
     149        InitializeCriticalSection(&mMessageQueueLock); 
     150 
    128151        // Create a thread to handle the named pipe 
    129152        HANDLE hThread; 
     
    264287{ 
    265288        mpCommandSocketInfo = new CommandSocketInfo; 
    266         this->mReceivedCommandConn = false; 
     289        WinNamedPipeStream& rSocket(mpCommandSocketInfo->mListeningSocket); 
    267290 
    268291        // loop until the parent process exits 
    269         while (TRUE) 
     292        while (!IsTerminateWanted()) 
    270293        { 
    271294                try 
    272295                { 
    273                         mpCommandSocketInfo->mListeningSocket.Accept( 
    274                                 BOX_NAMED_PIPE_NAME); 
     296                        rSocket.Accept(BOX_NAMED_PIPE_NAME); 
     297                } 
     298                catch (BoxException &e) 
     299                { 
     300                        ::syslog(LOG_ERR, "Failed to open command socket: %s", 
     301                                e.what()); 
     302                        SetTerminateWanted(); 
     303                        break; // this is fatal 
     304                } 
     305                catch (...) 
     306                { 
     307                        ::syslog(LOG_ERR, "Failed to open command socket: " 
     308                                "unknown error"); 
     309                        SetTerminateWanted(); 
     310                        break; // this is fatal 
     311                } 
     312 
     313                try 
     314                { 
     315                        // Errors here do not kill the thread, 
     316                        // only the current connection. 
    275317 
    276318                        // This next section comes from Ben's original function 
     
    290332                                mState); 
    291333 
    292                         mpCommandSocketInfo->mListeningSocket.Write(summary, summarySize); 
    293                         mpCommandSocketInfo->mListeningSocket.Write("ping\n", 5); 
    294  
    295                         IOStreamGetLine readLine(mpCommandSocketInfo->mListeningSocket); 
     334                        rSocket.Write(summary, summarySize); 
     335                        rSocket.Write("ping\n", 5); 
     336 
     337                        // old queued messages are not useful 
     338                        EnterCriticalSection(&mMessageQueueLock); 
     339                        mMessageList.clear(); 
     340                        ResetEvent(mhMessageToSendEvent); 
     341                        LeaveCriticalSection(&mMessageQueueLock); 
     342 
     343                        IOStreamGetLine readLine(rSocket); 
    296344                        std::string command; 
    297345 
    298                         while (mpCommandSocketInfo->mListeningSocket.IsConnected() && 
    299                                readLine.GetLine(command) ) 
    300                         { 
    301                                 TRACE1("Receiving command '%s' over " 
    302                                         "command socket\n", command.c_str()); 
     346                        while (rSocket.IsConnected() && !IsTerminateWanted()) 
     347                        { 
     348                                HANDLE handles[2]; 
     349                                handles[0] = mhMessageToSendEvent; 
     350                                handles[1] = rSocket.GetReadableEvent(); 
     351 
     352                                DWORD result = WaitForMultipleObjects( 
     353                                        sizeof(handles)/sizeof(*handles), 
     354                                        handles, FALSE, 1000); 
     355 
     356                                if (result == 0) 
     357                                { 
     358                                        ResetEvent(mhMessageToSendEvent); 
     359 
     360                                        EnterCriticalSection(&mMessageQueueLock); 
     361                                        try 
     362                                        { 
     363                                                while (mMessageList.size() > 0) 
     364                                                { 
     365                                                        std::string message = *(mMessageList.begin()); 
     366                                                        mMessageList.erase(mMessageList.begin()); 
     367                                                        printf("Sending '%s' to waiting client... ", message.c_str()); 
     368                                                        message += "\n"; 
     369                                                        rSocket.Write(message.c_str(), 
     370                                                                message.length()); 
     371 
     372                                                        printf("done.\n"); 
     373                                                } 
     374                                        } 
     375                                        catch (...) 
     376                                        { 
     377                                                LeaveCriticalSection(&mMessageQueueLock); 
     378                                                throw; 
     379                                        } 
     380                                        LeaveCriticalSection(&mMessageQueueLock); 
     381                                        continue; 
     382                                } 
     383                                else if (result == WAIT_TIMEOUT) 
     384                                { 
     385                                        continue; 
     386                                } 
     387                                else if (result != 1) 
     388                                { 
     389                                        ::syslog(LOG_ERR, "WaitForMultipleObjects returned invalid result %d", result); 
     390                                        continue; 
     391                                } 
     392 
     393                                if (!readLine.GetLine(command)) 
     394                                { 
     395                                        ::syslog(LOG_ERR, "Failed to read line"); 
     396                                        continue; 
     397                                } 
     398 
     399                                printf("Received command '%s' from client\n", command.c_str()); 
    303400 
    304401                                bool sendOK = false; 
     
    339436                                        sendOK = true; 
    340437                                } 
     438                                else 
     439                                { 
     440                                        ::syslog(LOG_ERR, "Received unknown command '%s' from client", command.c_str()); 
     441                                        sendResponse = true; 
     442                                        sendOK = false; 
     443                                } 
    341444 
    342445                                // Send a response back? 
     
    344447                                { 
    345448                                        const char* response = sendOK ? "ok\n" : "error\n"; 
    346                                         mpCommandSocketInfo->mListeningSocket.Write( 
     449                                        rSocket.Write( 
    347450                                                response, strlen(response)); 
    348451                                } 
     
    353456                                } 
    354457 
    355                                 this->mReceivedCommandConn = true; 
    356                         } 
    357  
    358                         mpCommandSocketInfo->mListeningSocket.Close(); 
     458                                // this->mReceivedCommandConn = true; 
     459                        } 
     460 
     461                        rSocket.Close(); 
    359462                } 
    360463                catch (BoxException &e) 
     
    505608        // haven't contacted the store yet 
    506609 
    507         bool deserialised = DeserializeStoreObjectInfo(clientStoreMarker,  
    508                 lastSyncTime, nextSyncTime); 
     610        bool deleteStoreObjectInfoFile = DeserializeStoreObjectInfo( 
     611                clientStoreMarker, lastSyncTime, nextSyncTime); 
    509612  
    510613        // -------------------------------------------------------------------------------------------- 
     
    612715                        // so that we don't try to reload it after a 
    613716                        // partially completed backup 
    614                         if(deserialised && !DeleteStoreObjectInfo()) 
     717                        if(deleteStoreObjectInfoFile &&  
     718                                !DeleteStoreObjectInfo()) 
    615719                        { 
    616720                                ::syslog(LOG_ERR, "Failed to delete the " 
     
    622726                                continue; 
    623727                        } 
     728 
     729                        // In case the backup throws an exception, 
     730                        // we should not try to delete the store info 
     731                        // object file again. 
     732                        deleteStoreObjectInfoFile = false; 
    624733                         
    625734                        // Do sync 
     
    730839                                // -------------------------------------------------------------------------------------------- 
    731840 
    732                                 // We had a successful backup, save the store info 
    733                                 SerializeStoreObjectInfo(clientStoreMarker, lastSyncTime, nextSyncTime); 
     841                                // We had a successful backup, save the store  
     842                                // info. If we save successfully, we must  
     843                                // delete the file next time we start a backup 
     844 
     845                                deleteStoreObjectInfoFile =  
     846                                        SerializeStoreObjectInfo( 
     847                                                clientStoreMarker,  
     848                                                lastSyncTime, nextSyncTime); 
    734849 
    735850                                // -------------------------------------------------------------------------------------------- 
     
    9031018{ 
    9041019#ifdef WIN32 
    905         // Really could use some interprocess protection, mutex etc 
    906         // any side effect should be too bad???? :) 
    907         DWORD timeout = (DWORD)BoxTimeToMilliSeconds(RequiredDelay); 
    908  
    909         while ( this->mReceivedCommandConn == false ) 
    910         { 
    911                 Sleep(1); 
    912  
    913                 if ( timeout == 0 ) 
    914                 { 
    915                         DoSyncFlagOut = false; 
    916                         SyncIsForcedOut = false; 
    917                         return; 
    918                 } 
    919                 timeout--; 
    920         } 
    921         this->mReceivedCommandConn = false; 
    922         DoSyncFlagOut = this->mDoSyncFlagOut; 
    923         SyncIsForcedOut = this->mSyncIsForcedOut; 
     1020        DWORD requiredDelayMs = BoxTimeToMilliSeconds(RequiredDelay); 
     1021 
     1022        DWORD result = WaitForSingleObject(mhCommandReceivedEvent,  
     1023                (DWORD)requiredDelayMs); 
     1024 
     1025        if (result == WAIT_OBJECT_0) 
     1026        { 
     1027                DoSyncFlagOut = this->mDoSyncFlagOut; 
     1028                SyncIsForcedOut = this->mSyncIsForcedOut; 
     1029                ResetEvent(mhCommandReceivedEvent); 
     1030        } 
     1031        else if (result == WAIT_TIMEOUT) 
     1032        { 
     1033                DoSyncFlagOut = false; 
     1034                SyncIsForcedOut = false; 
     1035        } 
     1036        else 
     1037        { 
     1038                ::syslog(LOG_ERR, "Unexpected result from " 
     1039                        "WaitForSingleObject: error %d", GetLastError()); 
     1040        } 
    9241041 
    9251042        return; 
     
    9541071#ifdef PLATFORM_CANNOT_FIND_PEER_UID_OF_UNIX_SOCKET 
    9551072                                bool uidOK = true; 
    956                                 ::syslog(LOG_WARNING, "On this platform, no security check can be made on the credientials of peers connecting to the command socket. (bbackupctl)"); 
     1073                                ::syslog(LOG_WARNING, "On this platform, no security check can be made on the credentials of peers connecting to the command socket. (bbackupctl)"); 
    9571074#else 
    9581075                                // Security check -- does the process connecting to this socket have 
     
    10241141                        && mpCommandSocketInfo->mpGetLine->GetLine(command, false /* no preprocessing */, timeout)) 
    10251142                { 
    1026                         TRACE1("Receiving command '%s' over command socket\n", command.c_str()); 
    1027                          
     1143                        TRACE1("Receiving command '%s' over command socket\n",  
     1144                                command.c_str()); 
     1145 
     1146                        #ifdef WIN32 
     1147                        SetEvent(mhCommandReceivedEvent); 
     1148                        #endif 
     1149 
    10281150                        bool sendOK = false; 
    10291151                        bool sendResponse = true; 
     
    11381260void BackupDaemon::SendSyncStartOrFinish(bool SendStart) 
    11391261{ 
    1140         // The bbackupctl program can't rely on a state change, because it may never 
    1141         // change if the server doesn't need to be contacted. 
    1142  
    1143 #ifdef __MINGW32__ 
    1144 #warning race condition: what happens if socket is closed? 
    1145 #endif 
     1262        // The bbackupctl program can't rely on a state change, because it  
     1263        // may never change if the server doesn't need to be contacted. 
    11461264 
    11471265        if (mpCommandSocketInfo != NULL && 
     
    11531271            ) 
    11541272        { 
    1155                 const char* message = SendStart ? "start-sync\n" : "finish-sync\n"; 
     1273                std::string message = SendStart ? "start-sync" : "finish-sync"; 
    11561274                try 
    11571275                { 
    11581276#ifdef WIN32 
    1159                         mpCommandSocketInfo->mListeningSocket.Write(message,  
    1160                                 (int)strlen(message)); 
     1277                        EnterCriticalSection(&mMessageQueueLock); 
     1278                        mMessageList.push_back(message); 
     1279                        SetEvent(mhMessageToSendEvent); 
     1280                        LeaveCriticalSection(&mMessageQueueLock); 
    11611281#else 
    1162                         mpCommandSocketInfo->mpConnectedSocket->Write(message, 
    1163                                 strlen(message)); 
     1282                        message += "\n"; 
     1283                        mpCommandSocketInfo->mpConnectedSocket->Write( 
     1284                                message.c_str(), message.size()); 
    11641285#endif 
    11651286                } 
     
    17571878 
    17581879        char newState[64]; 
    1759         char newStateSize = sprintf(newState, "state %d\n", State); 
     1880        sprintf(newState, "state %d", State); 
     1881        std::string message = newState; 
    17601882 
    17611883#ifdef WIN32 
    1762         #ifndef _MSC_VER 
    1763                 #warning FIX ME: race condition 
    1764         #endif 
    1765  
    1766         // what happens if the socket is closed by the other thread before 
    1767         // we can write to it? Null pointer deref at best. 
    1768         if (mpCommandSocketInfo &&  
    1769             mpCommandSocketInfo->mListeningSocket.IsConnected()) 
    1770         { 
    1771                 try 
    1772                 { 
    1773                         mpCommandSocketInfo->mListeningSocket.Write(newState, newStateSize); 
    1774                 } 
    1775                 catch(...) 
    1776                 { 
    1777                         CloseCommandConnection(); 
    1778                 } 
    1779         } 
     1884        EnterCriticalSection(&mMessageQueueLock); 
     1885        mMessageList.push_back(newState); 
     1886        SetEvent(mhMessageToSendEvent); 
     1887        LeaveCriticalSection(&mMessageQueueLock); 
    17801888#else 
    1781         if(mpCommandSocketInfo != 0 && mpCommandSocketInfo->mpConnectedSocket.get() != 0) 
    1782         { 
    1783                 // Something connected to the command socket, tell it about the new state 
    1784                 try 
    1785                 { 
    1786                         mpCommandSocketInfo->mpConnectedSocket->Write(newState, newStateSize); 
    1787                 } 
    1788                 catch(...) 
    1789                 { 
    1790                         CloseCommandConnection(); 
    1791                 } 
     1889        message += "\n"; 
     1890 
     1891        if(mpCommandSocketInfo == 0) 
     1892        { 
     1893                return; 
     1894        } 
     1895 
     1896        if (mpCommandSocketInfo->mpConnectedSocket.get() == 0) 
     1897        { 
     1898                return; 
     1899        } 
     1900 
     1901        // Something connected to the command socket, tell it about the new state 
     1902        try 
     1903        { 
     1904                mpCommandSocketInfo->mpConnectedSocket->Write(message.c_str(), 
     1905                        message.length()); 
     1906        } 
     1907        catch(...) 
     1908        { 
     1909                CloseCommandConnection(); 
    17921910        } 
    17931911#endif 
     
    21742292static const int STOREOBJECTINFO_VERSION = 1; 
    21752293 
    2176 void BackupDaemon::SerializeStoreObjectInfo(int64_t aClientStoreMarker, box_time_t theLastSyncTime, box_time_t theNextSyncTime) const 
     2294bool BackupDaemon::SerializeStoreObjectInfo(int64_t aClientStoreMarker, box_time_t theLastSyncTime, box_time_t theNextSyncTime) const 
    21772295{ 
    21782296        if(!GetConfiguration().KeyExists("StoreObjectInfoFile")) 
    21792297        { 
    2180                 return; 
     2298                return false; 
    21812299        } 
    21822300 
     
    21862304        if (StoreObjectInfoFile.size() <= 0) 
    21872305        { 
    2188                 return; 
    2189         } 
     2306                return false; 
     2307        } 
     2308 
     2309        bool created = false; 
    21902310 
    21912311        try 
     
    21932313                FileStream aFile(StoreObjectInfoFile.c_str(),  
    21942314                        O_WRONLY | O_CREAT | O_TRUNC); 
     2315                created = true; 
     2316 
    21952317                Archive anArchive(aFile, 0); 
    21962318 
     
    22372359                        StoreObjectInfoFile.c_str()); 
    22382360        } 
     2361 
     2362        return created; 
    22392363} 
    22402364 
  • box/chris/merge/bin/bbackupd/BackupDaemon.h

    r456 r710  
    4747 
    4848private: 
    49         // methods below do partial (specialized) serialization of client state only 
    50         void SerializeStoreObjectInfo(int64_t aClientStoreMarker, box_time_t theLastSyncTime, box_time_t theNextSyncTime) const; 
    51         bool DeserializeStoreObjectInfo(int64_t & aClientStoreMarker, box_time_t & theLastSyncTime, box_time_t & theNextSyncTime); 
     49        // methods below do partial (specialized) serialization of  
     50        // client state only 
     51        bool SerializeStoreObjectInfo(int64_t aClientStoreMarker,  
     52                box_time_t theLastSyncTime, box_time_t theNextSyncTime) const; 
     53        bool DeserializeStoreObjectInfo(int64_t & aClientStoreMarker,  
     54                box_time_t & theLastSyncTime, box_time_t & theNextSyncTime); 
    5255        bool DeleteStoreObjectInfo() const; 
    5356        BackupDaemon(const BackupDaemon &); 
     
    183186 
    184187        private: 
    185         bool mDoSyncFlagOut, mSyncIsForcedOut, mReceivedCommandConn; 
     188        bool mDoSyncFlagOut, mSyncIsForcedOut; 
     189        HANDLE mhMessageToSendEvent, mhCommandReceivedEvent; 
     190        CRITICAL_SECTION mMessageQueueLock; 
     191        std::vector<std::string> mMessageList; 
    186192#endif 
    187193}; 
  • box/chris/merge/bin/bbackupd/Win32BackupService.cpp

    r217 r710  
    1313#include "Win32BackupService.h" 
    1414 
    15 Win32BackupService gDaemonService; 
     15Win32BackupService* gpDaemonService = NULL; 
    1616extern HANDLE gStopServiceEvent; 
    1717 
    1818unsigned int WINAPI RunService(LPVOID lpParameter) 
    1919{ 
    20         DWORD retVal = gDaemonService.WinService(); 
    21         SetEvent( gStopServiceEvent ); 
     20        DWORD retVal = gpDaemonService->WinService((const char*) lpParameter); 
     21        SetEvent(gStopServiceEvent); 
    2222        return retVal; 
    2323} 
     
    2525void TerminateService(void) 
    2626{ 
    27         gDaemonService.SetTerminateWanted(); 
     27        gpDaemonService->SetTerminateWanted(); 
    2828} 
    2929 
    30 DWORD Win32BackupService::WinService(void) 
     30DWORD Win32BackupService::WinService(const char* pConfigFileName) 
    3131{ 
    32         int argc = 2; 
    33         //first off get the path name for the default  
    34         char buf[MAX_PATH]; 
     32        char exepath[MAX_PATH]; 
     33        GetModuleFileName(NULL, exepath, sizeof(exepath)); 
     34 
     35        std::string configfile; 
    3536         
    36         GetModuleFileName(NULL, buf, sizeof(buf)); 
    37         std::string buffer(buf); 
    38         std::string conf( "-c"); 
    39         std::string cfile(buffer.substr(0,(buffer.find("bbackupd.exe")))  
    40                         + "bbackupd.conf"); 
     37        if (pConfigFileName != NULL) 
     38        { 
     39                configfile = pConfigFileName; 
     40        } 
     41        else 
     42        { 
     43                // make the default config file name, 
     44                // based on the program path 
     45                configfile = exepath; 
     46                configfile = configfile.substr(0, 
     47                        configfile.rfind(DIRECTORY_SEPARATOR_ASCHAR)); 
     48                configfile += DIRECTORY_SEPARATOR "bbackupd.conf"; 
     49        } 
    4150 
    42         const char *argv[] = {conf.c_str(), cfile.c_str()}; 
     51        const char *argv[] = {exepath, "-c", configfile.c_str()}; 
     52        int argc = sizeof(argv) / sizeof(*argv); 
     53        DWORD ret; 
    4354 
    4455        MAINHELPER_START 
     56        ret = this->Main(BOX_FILE_BBACKUPD_DEFAULT_CONFIG, argc, argv); 
     57        MAINHELPER_END 
    4558 
    46         return this->Main(BOX_FILE_BBACKUPD_DEFAULT_CONFIG, argc, argv); 
    47  
    48         MAINHELPER_END 
     59        return ret; 
    4960} 
    5061 
  • box/chris/merge/bin/bbackupd/Win32BackupService.h

    r217 r710  
    1313{ 
    1414public: 
    15         DWORD WinService(void); 
     15        DWORD WinService(const char* pConfigFileName); 
    1616}; 
    1717 
  • box/chris/merge/bin/bbackupd/Win32ServiceFunctions.cpp

    r456 r710  
    9494// service cannot start if there is an eror. 
    9595 
     96static char* spConfigFileName; 
     97 
    9698VOID ServiceMain(DWORD argc, LPTSTR *argv)  
    9799{ 
    98     // initialise service status 
    99     gServiceStatus.dwServiceType = SERVICE_WIN32; 
    100     gServiceStatus.dwCurrentState = SERVICE_STOPPED; 
    101     gServiceStatus.dwControlsAccepted = 0; 
    102     gServiceStatus.dwWin32ExitCode = NO_ERROR; 
    103     gServiceStatus.dwServiceSpecificExitCode = NO_ERROR; 
    104     gServiceStatus.dwCheckPoint = 0; 
    105     gServiceStatus.dwWaitHint = 0; 
    106  
    107     gServiceStatusHandle = RegisterServiceCtrlHandler(gServiceName,  
    108         ServiceControlHandler); 
    109  
    110     if (gServiceStatusHandle) 
    111     { 
    112         // service is starting 
    113         gServiceStatus.dwCurrentState = SERVICE_START_PENDING; 
    114         SetServiceStatus(gServiceStatusHandle, &gServiceStatus); 
    115  
    116         // do initialisation here 
    117         gStopServiceEvent = CreateEvent( 0, TRUE, FALSE, 0 ); 
     100        // initialise service status 
     101        gServiceStatus.dwServiceType = SERVICE_WIN32; 
     102        gServiceStatus.dwCurrentState = SERVICE_STOPPED; 
     103        gServiceStatus.dwControlsAccepted = 0; 
     104        gServiceStatus.dwWin32ExitCode = NO_ERROR; 
     105        gServiceStatus.dwServiceSpecificExitCode = NO_ERROR; 
     106        gServiceStatus.dwCheckPoint = 0; 
     107        gServiceStatus.dwWaitHint = 0; 
     108 
     109        gServiceStatusHandle = RegisterServiceCtrlHandler(gServiceName,  
     110                ServiceControlHandler); 
     111 
     112        if (gServiceStatusHandle) 
     113        { 
     114                // service is starting 
     115                gServiceStatus.dwCurrentState = SERVICE_START_PENDING; 
     116                SetServiceStatus(gServiceStatusHandle, &gServiceStatus); 
     117 
     118                // do initialisation here 
     119                gStopServiceEvent = CreateEvent(0, TRUE, FALSE, 0); 
    118120                if (!gStopServiceEvent) 
    119121                { 
     
    130132                        0, 
    131133                        RunService, 
    132                         0, 
     134                        spConfigFileName, 
    133135                        CREATE_SUSPENDED, 
    134136                        NULL); 
     
    139141                // we are now running so tell the SCM 
    140142                gServiceStatus.dwControlsAccepted |=  
    141                 (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); 
     143                        (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); 
    142144                gServiceStatus.dwCurrentState = SERVICE_RUNNING; 
    143145                SetServiceStatus(gServiceStatusHandle, &gServiceStatus); 
     
    157159                gServiceStatus.dwCurrentState = SERVICE_STOPPED; 
    158160                SetServiceStatus(gServiceStatusHandle, &gServiceStatus); 
    159     } 
    160 } 
    161  
    162 void OurService(void) 
    163 { 
     161        } 
     162} 
     163 
     164void OurService(char* pConfigFileName) 
     165{ 
     166        spConfigFileName = pConfigFileName; 
     167 
    164168        SERVICE_TABLE_ENTRY serviceTable[] =  
    165169        {  
     
    180184} 
    181185 
    182 void InstallService(void) 
    183 { 
    184         SC_HANDLE newService, scm; 
    185  
    186         scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE); 
     186int InstallService(const char* pConfigFileName) 
     187{ 
     188        if (pConfigFileName != NULL) 
     189        { 
     190                struct stat st; 
     191 
     192                if (emu_stat(pConfigFileName, &st) != 0) 
     193                { 
     194                        syslog(LOG_ERR, "Failed to open configuration file: " 
     195                                "%s: %s", pConfigFileName, strerror(errno)); 
     196                        return 1; 
     197                } 
     198 
     199                if (! st.st_mode & S_IFREG) 
     200                { 
     201         
     202                        syslog(LOG_ERR, "Failed to open configuration file: " 
     203                                "%s: not a file", pConfigFileName); 
     204                        return 1; 
     205                } 
     206        } 
     207 
     208        SC_HANDLE scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE); 
    187209 
    188210        if (!scm)  
     
    190212                syslog(LOG_ERR, "Failed to open service control manager: " 
    191213                        "error %d", GetLastError()); 
    192                 return; 
     214                return 1; 
    193215        } 
    194216 
     
    197219        cmd[sizeof(cmd)-1] = 0; 
    198220 
    199         char cmd_args[MAX_PATH]; 
    200         _snprintf(cmd_args, sizeof(cmd_args)-1, "%s --service", cmd); 
    201         cmd_args[sizeof(cmd_args)-1] = 0; 
    202  
    203         newService = CreateService( 
     221        std::string cmdWithArgs(cmd); 
     222        cmdWithArgs += " --service"; 
     223 
     224        if (pConfigFileName != NULL) 
     225        { 
     226                cmdWithArgs += " \""; 
     227                cmdWithArgs += pConfigFileName; 
     228                cmdWithArgs += "\""; 
     229        } 
     230 
     231        SC_HANDLE newService = CreateService( 
    204232                scm,  
    205233                SERVICE_NAME,  
     
    209237                SERVICE_AUTO_START,  
    210238                SERVICE_ERROR_NORMAL,  
    211                 cmd_args,  
     239                cmdWithArgs.c_str(), 
    212240                0,0,0,0,0); 
    213241 
     242        DWORD err = GetLastError(); 
     243        CloseServiceHandle(scm); 
     244 
    214245        if (!newService)  
    215246        { 
    216                 ::syslog(LOG_ERR, "Failed to create Box Backup service: " 
    217                         "error %d", GetLastError()); 
    218                 return; 
     247                if (err == ERROR_SERVICE_EXISTS) 
     248                { 
     249                        ::syslog(LOG_ERR, "Failed to create Box Backup " 
     250                                "service: it already exists"); 
     251                } 
     252                else if (err == ERROR_SERVICE_MARKED_FOR_DELETE) 
     253                { 
     254                        ::syslog(LOG_ERR, "Failed to create Box Backup " 
     255                                "service: it is waiting to be deleted"); 
     256                } 
     257                else if (err == ERROR_DUPLICATE_SERVICE_NAME) 
     258                { 
     259                        ::syslog(LOG_ERR, "Failed to create Box Backup " 
     260                                "service: a service with this name " 
     261                                "already exists"); 
     262                } 
     263                else 
     264                { 
     265                        ::syslog(LOG_ERR, "Failed to create Box Backup " 
     266                                "service: error %d", err); 
     267                } 
     268                return 1; 
    219269        } 
    220270 
     
    232282 
    233283        CloseServiceHandle(newService); 
    234         CloseServiceHandle(scm); 
    235 } 
    236  
    237 void RemoveService(void) 
    238 { 
    239         SC_HANDLE service, scm; 
    240         SERVICE_STATUS status; 
    241  
    242         scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE); 
     284 
     285        return 0; 
     286} 
     287 
     288int RemoveService(void) 
     289{ 
     290        SC_HANDLE scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE); 
    243291 
    244292        if (!scm)  
     
    246294                syslog(LOG_ERR, "Failed to open service control manager: " 
    247295                        "error %d", GetLastError()); 
    248                 return; 
    249         } 
    250  
    251         service = OpenService(scm, SERVICE_NAME, SERVICE_ALL_ACCESS|DELETE); 
    252         ControlService(service, SERVICE_CONTROL_STOP, &status); 
     296                return 1; 
     297        } 
     298 
     299        SC_HANDLE service = OpenService(scm, SERVICE_NAME,  
     300                SERVICE_ALL_ACCESS|DELETE); 
     301        DWORD err = GetLastError(); 
     302        CloseServiceHandle(scm); 
    253303 
    254304        if (!service) 
    255305        { 
    256                 syslog(LOG_ERR, "Failed to open Box Backup service: " 
    257                         "error %d", GetLastError()); 
    258                 return; 
    259         } 
    260  
    261         if (DeleteService(service)) 
     306                if (err == ERROR_SERVICE_DOES_NOT_EXIST || 
     307                        err == ERROR_IO_PENDING)  
     308                        // hello microsoft? anyone home? 
     309                { 
     310                        syslog(LOG_ERR, "Failed to open Box Backup service: " 
     311                                "not installed or not found"); 
     312                } 
     313                else 
     314                { 
     315                        syslog(LOG_ERR, "Failed to open Box Backup service: " 
     316                                "error %d", err); 
     317                } 
     318                return 1; 
     319        } 
     320 
     321        SERVICE_STATUS status; 
     322        if (!ControlService(service, SERVICE_CONTROL_STOP, &status)) 
     323        { 
     324                err = GetLastError(); 
     325                if (err != ERROR_SERVICE_NOT_ACTIVE) 
     326                { 
     327                        syslog(LOG_WARNING, "Failed to stop Box Backup " 
     328                                "service: error %d", err); 
     329                } 
     330        } 
     331 
     332        BOOL deleted = DeleteService(service); 
     333        err = GetLastError(); 
     334        CloseServiceHandle(service); 
     335 
     336        if (deleted) 
    262337        { 
    263338                syslog(LOG_INFO, "Box Backup service deleted"); 
     339                return 0; 
     340        } 
     341        else if (err == ERROR_SERVICE_MARKED_FOR_DELETE) 
     342        { 
     343                syslog(LOG_ERR, "Failed to remove Box Backup service: " 
     344                        "it is already being deleted"); 
    264345        } 
    265346        else 
    266347        { 
    267348                syslog(LOG_ERR, "Failed to remove Box Backup service: " 
    268                         "error %d", GetLastError()); 
    269         } 
    270  
    271         CloseServiceHandle(service); 
    272         CloseServiceHandle(scm); 
     349                        "error %d", err); 
     350        } 
     351 
     352        return 1; 
    273353} 
    274354 
  • box/chris/merge/bin/bbackupd/Win32ServiceFunctions.h

    r217 r710  
    1313#define WIN32SERVICEFUNCTIONS_H 
    1414 
    15 void RemoveService(void); 
    16 void InstallService(void); 
    17 void OurService(void); 
     15int RemoveService(void); 
     16int  InstallService(const char* pConfigFilePath); 
     17void OurService(char* pConfigFileName); 
    1818 
    1919#endif 
  • box/chris/merge/bin/bbackupd/bbackupd.cpp

    r456 r710  
    2020        #include "Win32BackupService.h" 
    2121 
    22         extern Win32BackupService gDaemonService; 
     22        extern Win32BackupService* gpDaemonService; 
    2323#endif 
    2424 
     
    2929#ifdef WIN32 
    3030 
    31         ::openlog("Box Backup (bbackupd)", 0, 0); 
     31        ::openlog("Box Backup (bbackupd)", LOG_PID, LOG_LOCAL6); 
    3232 
    3333        if(argc == 2 && 
     
    4141        if(argc == 2 && ::strcmp(argv[1], "-r") == 0) 
    4242        { 
    43                 RemoveService(); 
    44                 return 0; 
     43                return RemoveService(); 
    4544        } 
    46         if(argc == 2 && ::strcmp(argv[1], "-i") == 0) 
     45        if((argc == 2 || argc == 3) && ::strcmp(argv[1], "-i") == 0) 
    4746        { 
    48                 InstallService(); 
    49                 return 0; 
     47                const char* config = NULL; 
     48                if (argc == 3) 
     49                { 
     50                        config = argv[2]; 
     51                } 
     52                return InstallService(config); 
    5053        } 
    5154 
    5255        bool runAsWin32Service = false; 
    53         if (argc == 2 && ::strcmp(argv[1], "--service") == 0) 
     56        if (argc >= 2 && ::strcmp(argv[1], "--service") == 0) 
    5457        { 
    5558                runAsWin32Service = true; 
    5659        } 
    57          
    58         // Under win32 we must initialise the Winsock library 
    59         // before using sockets 
    60                  
    61         WSADATA info; 
    6260 
    63         if (WSAStartup(0x0101, &info) == SOCKET_ERROR)  
    64         { 
    65                 // box backup will not run without sockets 
    66                 ::syslog(LOG_ERR, "Failed to initialise Windows Sockets"); 
    67                 THROW_EXCEPTION(BackupStoreException, Internal) 
    68         } 
     61        gpDaemonService = new Win32BackupService(); 
    6962 
    7063        EnableBackupRights(); 
     
    7467        if (runAsWin32Service) 
    7568        { 
    76                 syslog(LOG_INFO,"Starting Box Backup Service"); 
    77                 OurService(); 
     69                syslog(LOG_INFO, "Box Backup service starting"); 
     70 
     71                char* config = NULL; 
     72                if (argc >= 3) 
     73                { 
     74                        config = strdup(argv[2]); 
     75                } 
     76 
     77                OurService(config); 
     78 
     79                if (config) 
     80                { 
     81                        free(config); 
     82                } 
     83 
     84                syslog(LOG_INFO, "Box Backup service shut down"); 
    7885        } 
    7986        else 
    8087        { 
    81                 ExitCode = gDaemonService.Main( 
     88                ExitCode = gpDaemonService->Main( 
    8289                        BOX_FILE_BBACKUPD_DEFAULT_CONFIG, argc, argv); 
    8390        } 
    8491 
    85         // Clean up our sockets 
    86         WSACleanup(); 
     92        ::closelog(); 
    8793 
    88         ::closelog(); 
     94        delete gpDaemonService; 
    8995 
    9096        return ExitCode; 
  • box/chris/merge/bin/bbackupquery/BackupQueries.cpp

    r626 r710  
    7171          mReturnCode(0)                // default return code 
    7272{ 
     73        #ifdef WIN32 
     74        mRunningAsRoot = TRUE; 
     75        #else 
    7376        mRunningAsRoot = (::geteuid() == 0); 
     77        #endif 
    7478} 
    7579 
     
    8589{ 
    8690} 
     91 
     92typedef struct cmd_info 
     93{ 
     94        const char* name; 
     95        const char* opts; 
     96} cmd_info_t; 
    8797 
    8898// -------------------------------------------------------------------------- 
     
    163173         
    164174        // Data about commands 
    165         static const char *commandNames[] = {"quit", "exit", "list",     "pwd", "cd", "lcd",    "sh", "getobject", "get", "compare", "restore", "help", "usage", "undelete", 0}; 
    166         static const char *validOptions[] = {"",         "",     "rodIFtsh", "",           "od", "",    "",       "",              "i",   "alcqE",   "dri",     "",     "",      "",             0}; 
     175        static cmd_info_t commands[] =  
     176        { 
     177                { "quit", "" }, 
     178                { "exit", "" }, 
     179                { "list", "rodIFtTsh", }, 
     180                { "pwd",  "" }, 
     181                { "cd",   "od" }, 
     182                { "lcd",  "" }, 
     183                { "sh",   "" }, 
     184                { "getobject", "" }, 
     185                { "get",  "i" }, 
     186                { "compare", "alcqAE" }, 
     187                { "restore", "dri" }, 
     188                { "help", "" }, 
     189                { "usage", "" }, 
     190                { "undelete", "" }, 
     191                { NULL, NULL }  
     192        }; 
    167193        #define COMMAND_Quit            0 
    168194        #define COMMAND_Exit            1 
     
    184210        // Work out which command it is... 
    185211        int cmd = 0; 
    186         while(commandNames[cmd] != 0 && ::strcmp(cmdElements[0].c_str(), commandNames[cmd]) != 0) 
     212        while(commands[cmd].name != 0 && ::strcmp(cmdElements[0].c_str(), commands[cmd].name) != 0) 
    187213        { 
    188214                cmd++; 
    189215        } 
    190         if(commandNames[cmd] == 0) 
     216        if(commands[cmd].name == 0) 
    191217        { 
    192218                // Check for aliases 
     
    223249                { 
    224250                        // Valid option? 
    225                         if(::strchr(validOptions[cmd], *c) == NULL) 
    226                         { 
    227                                 printf("Invalid option '%c' for command %s\n", *c, commandNames[cmd]); 
     251                        if(::strchr(commands[cmd].opts, *c) == NULL) 
     252                        { 
     253                                printf("Invalid option '%c' for command %s\n",  
     254                                        *c, commands[cmd].name); 
    228255                                return; 
    229256                        } 
     
    320347        #define LIST_OPTION_ALLOWDELETED        'd' 
    321348        #define LIST_OPTION_NOOBJECTID          'I' 
    322         #define LIST_OPTION_NOFLAGS                     'F' 
    323         #define LIST_OPTION_TIMES                       't' 
     349        #define LIST_OPTION_NOFLAGS             'F' 
     350        #define LIST_OPTION_TIMES_LOCAL         't' 
     351        #define LIST_OPTION_TIMES_UTC           'T' 
    324352        #define LIST_OPTION_SIZEINBLOCKS        's' 
    325353        #define LIST_OPTION_DISPLAY_HASH        'h' 
     
    363391// 
    364392// Function 
    365 //              Name:    BackupQueries::CommandList2(int64_t, const std::string &, const bool *) 
     393//              Name:    BackupQueries::List(int64_t, const std::string &, const bool *, bool) 
    366394//              Purpose: Do the actual listing of directories and files 
    367395//              Created: 2003/10/10 
     
    438466                } 
    439467                 
    440                 if(opts[LIST_OPTION_TIMES]) 
    441                 { 
    442                         // Show times... 
     468                if(opts[LIST_OPTION_TIMES_LOCAL]) 
     469                { 
     470                        // Show local times... 
    443471                        std::string time = BoxTimeToISO8601String( 
    444472                                en->GetModificationTime()); 
     
    845873 
    846874        // Find object ID somehow 
    847         int64_t id; 
     875        int64_t fileId; 
     876        int64_t dirId = GetCurrentDirectoryID(); 
    848877        std::string localName; 
     878 
    849879        // BLOCK 
    850880        { 
     881#ifdef WIN32 
     882                std::string fileName; 
     883                if(!ConvertConsoleToUtf8(args[0].c_str(), fileName)) 
     884                        return; 
     885#else 
     886                std::string fileName(args[0]); 
     887#endif 
     888 
     889                if(!opts['i']) 
     890                { 
     891                        // does this remote filename include a path? 
     892                        std::string::size_type index = fileName.rfind('/'); 
     893                        if(index != std::string::npos) 
     894                        { 
     895                                std::string dirName(fileName.substr(0, index)); 
     896                                fileName = fileName.substr(index + 1); 
     897 
     898                                dirId = FindDirectoryObjectID(dirName); 
     899                                if(dirId == 0) 
     900                                { 
     901                                        printf("Directory '%s' not found\n",  
     902                                                dirName.c_str()); 
     903                                        return; 
     904                                } 
     905                        } 
     906                } 
     907 
     908                BackupStoreFilenameClear fn(fileName); 
     909 
    851910                // Need to look it up in the current directory 
    852911                mrConnection.QueryListDirectory( 
    853                                 GetCurrentDirectoryID(), 
     912                                dirId, 
    854913                                BackupProtocolClientListDirectory::Flags_File,  // just files 
    855914                                (opts['i'])?(BackupProtocolClientListDirectory::Flags_EXCLUDE_NOTHING):(BackupProtocolClientListDirectory::Flags_OldVersion | BackupProtocolClientListDirectory::Flags_Deleted), // only current versions 
     
    864923                { 
    865924                        // Specified as ID.  
    866                         id = ::strtoll(args[0].c_str(), 0, 16); 
    867                         if(id == std::numeric_limits<long long>::min() || id == std::numeric_limits<long long>::max() || id == 0) 
     925                        fileId = ::strtoll(args[0].c_str(), 0, 16); 
     926                        if(fileId == std::numeric_limits<long long>::min() ||  
     927                                fileId == std::numeric_limits<long long>::max() ||  
     928                                fileId == 0) 
    868929                        { 
    869930                                printf("Not a valid object ID (specified in hex)\n"); 
     
    872933                         
    873934                        // Check that the item is actually in the directory 
    874                         if(dir.FindEntryByID(id) == 0) 
    875                         { 
    876                                 printf("ID '%08llx' not found in current directory on store.\n(You can only download objects by ID from the current directory.)\n", id); 
     935                        if(dir.FindEntryByID(fileId) == 0) 
     936                        { 
     937                                printf("ID '%08llx' not found in current " 
     938                                        "directory on store.\n" 
     939                                        "(You can only download objects by ID " 
     940                                        "from the current directory.)\n",  
     941                                        fileId); 
    877942                                return; 
    878943                        } 
     
    885950                        // Specified by name, find the object in the directory to get the ID 
    886951                        BackupStoreDirectory::Iterator i(dir); 
    887 #ifdef WIN32 
    888                         std::string fileName; 
    889                         if(!ConvertConsoleToUtf8(args[0].c_str(), fileName)) 
    890                                 return; 
    891                         BackupStoreFilenameClear fn(fileName); 
    892 #else 
    893                         BackupStoreFilenameClear fn(args[0]); 
    894 #endif 
    895952                        BackupStoreDirectory::Entry *en = i.FindMatchingClearName(fn); 
    896953                         
    897954                        if(en == 0) 
    898955                        { 
    899                                 printf("Filename '%s' not found in current directory on store.\n(Subdirectories in path not searched.)\n", args[0].c_str()); 
     956                                printf("Filename '%s' not found in current " 
     957                                        "directory on store.\n" 
     958                                        "(Subdirectories in path not " 
     959                                        "searched.)\n", args[0].c_str()); 
    900960                                return; 
    901961                        } 
    902962                         
    903                         id = en->GetObjectID(); 
     963                        fileId = en->GetObjectID(); 
    904964                         
    905                         // Local name is the last argument, which is either the looked up filename, or 
    906                         // a filename specified by the user. 
     965                        // Local name is the last argument, which is either  
     966                        // the looked up filename, or a filename specified  
     967                        // by the user. 
    907968                        localName = args[args.size() - 1]; 
    908969                } 
     
    921982        { 
    922983                // Request object 
    923                 mrConnection.QueryGetFile(GetCurrentDirectoryID(), id); 
     984                mrConnection.QueryGetFile(dirId, fileId); 
    924985 
    925986                // Stream containing encoded file 
     
    930991 
    931992                // Done. 
    932                 printf("Object ID %08llx fetched sucessfully.\n", id); 
     993                printf("Object ID %08llx fetched sucessfully.\n", fileId); 
    933994        } 
    934995        catch(...) 
     
    9511012        : mQuickCompare(false), 
    9521013          mIgnoreExcludes(false), 
     1014          mIgnoreAttributes(false), 
    9531015          mDifferences(0), 
    9541016          mDifferencesExplainedByModTime(0), 
     1017          mUncheckedFiles(0), 
    9551018          mExcludedDirs(0), 
    9561019          mExcludedFiles(0), 
     
    10131076        params.mQuickCompare = opts['q']; 
    10141077        params.mIgnoreExcludes = opts['E']; 
     1078        params.mIgnoreAttributes = opts['A']; 
    10151079         
    10161080        // Try and work out the time before which all files should be on the server 
     
    10751139        } 
    10761140         
    1077         printf("\n[ %d (of %d) differences probably due to file modifications after the last upload ]\nDifferences: %d (%d dirs excluded, %d files excluded)\n", 
    1078                 params.mDifferencesExplainedByModTime, params.mDifferences, params.mDifferences, params.mExcludedDirs, params.mExcludedFiles); 
     1141        printf("\n[ %d (of %d) differences probably due to file " 
     1142                "modifications after the last upload ]\n" 
     1143                "Differences: %d (%d dirs excluded, %d files excluded, " 
     1144                "%d files not checked)\n", 
     1145                params.mDifferencesExplainedByModTime, params.mDifferences,  
     1146                params.mDifferences, params.mExcludedDirs,  
     1147                params.mExcludedFiles, params.mUncheckedFiles); 
    10791148         
    10801149        // Set return code? 
    10811150        if(opts['c']) 
    10821151        { 
    1083                 SetReturnCode((params.mDifferences == 0)?COMPARE_RETURN_SAME:COMPARE_RETURN_DIFFERENT); 
     1152                if (params.mUncheckedFiles != 0) 
     1153                { 
     1154                        SetReturnCode(COMPARE_RETURN_ERROR); 
     1155                }  
     1156                else if (params.mDifferences != 0) 
     1157                { 
     1158                        SetReturnCode(COMPARE_RETURN_DIFFERENT); 
     1159                } 
     1160                else 
     1161                { 
     1162                        SetReturnCode(COMPARE_RETURN_SAME); 
     1163                } 
    10841164        } 
    10851165} 
     
    12151295                                localDirDisplay.c_str(),  
    12161296                                storeDirDisplay.c_str()); 
     1297                        rParams.mDifferences ++; 
    12171298                } 
    12181299                else 
     
    12201301                        printf("ERROR: stat on local dir '%s'\n",  
    12211302                                localDirDisplay.c_str()); 
     1303                        rParams.mUncheckedFiles ++; 
    12221304                } 
    12231305                return; 
     
    12691351                printf("ERROR: opendir on local dir '%s'\n",  
    12701352                        localDirDisplay.c_str()); 
     1353                rParams.mUncheckedFiles ++; 
    12711354                return; 
    12721355        } 
     
    14561539                                                 
    14571540                                                // Compare attributes 
     1541                                                box_time_t fileModTime = 0; 
    14581542                                                BackupClientFileAttributes localAttr; 
    1459                                                 box_time_t fileModTime = 0; 
    14601543                                                localAttr.ReadAttributes(localPath.c_str(), false /* don't zero mod times */, &fileModTime);                                     
    14611544                                                modifiedAfterLastSync = (fileModTime > rParams.mLatestFileUploadTime); 
    1462                                                 if(!localAttr.Compare(fileOnServerStream->GetAttributes(), 
     1545                                                if(!rParams.mIgnoreAttributes && 
     1546                                                   !localAttr.Compare(fileOnServerStream->GetAttributes(), 
    14631547                                                                true /* ignore attr mod time */, 
    14641548                                                                fileOnServerStream->IsSymLink() /* ignore modification time if it's a symlink */)) 
     
    15551639                                                e.GetSubType(), 
    15561640                                                storePathDisplay.c_str()); 
     1641                                        rParams.mUncheckedFiles ++; 
    15571642                                } 
    15581643                                catch(...) 
    1559                                 { 
     1644                                {        
    15601645                                        printf("ERROR: (unknown) during file fetch and comparison for '%s'\n", storePathDisplay.c_str()); 
     1646                                        rParams.mUncheckedFiles ++; 
    15611647                                } 
    15621648 
     
    17941880                break; 
    17951881                 
     1882        #ifdef WIN32 
     1883        case Restore_TargetPathNotFound: 
     1884                printf("The target directory path does not exist.\n" 
     1885                        "To restore to a directory whose parent " 
     1886                        "does not exist, create the parent first.\n"); 
     1887                break; 
     1888        #endif 
     1889 
    17961890        default: 
    17971891                printf("ERROR: Unknown restore result.\n"); 
  • box/chris/merge/bin/bbackupquery/BackupQueries.h

    r217 r710  
    6969                bool mQuickCompare; 
    7070                bool mIgnoreExcludes; 
     71                bool mIgnoreAttributes; 
    7172                int mDifferences; 
    7273                int mDifferencesExplainedByModTime; 
     74                int mUncheckedFiles; 
    7375                int mExcludedDirs; 
    7476                int mExcludedFiles; 
  • box/chris/merge/bin/bbackupquery/documentation.txt

    r217 r710  
    105105        -q -- quick compare. Only checks file contents against checksums, 
    106106                        doesn't do a full download 
     107        -A -- ignore attribute differences 
    107108        -E -- ignore exclusion settings 
    108109         
  • box/chris/merge/bin/bbstored/BBStoreDHousekeeping.cpp

    r250 r710  
    1111 
    1212#include <stdio.h> 
     13 
     14#ifdef HAVE_SYSLOG_H 
    1315#include <syslog.h> 
     16#endif 
    1417 
    1518#include "BackupStoreDaemon.h" 
     
    3033// 
    3134// -------------------------------------------------------------------------- 
     35void BackupStoreDaemon::HousekeepingInit() 
     36{ 
     37 
     38        mLastHousekeepingRun = 0; 
     39} 
     40 
     41#ifndef WIN32 
    3242void BackupStoreDaemon::HousekeepingProcess() 
    3343{ 
     44        HousekeepingInit(); 
     45 
    3446        // Get the time between housekeeping runs 
    3547        const Configuration &rconfig(GetConfiguration()); 
    3648        int64_t housekeepingInterval = SecondsToBoxTime(rconfig.GetKeyValueInt("TimeBetweenHousekeeping")); 
    37          
    38         int64_t lastHousekeepingRun = 0; 
    3949 
    4050        while(!StopRun()) 
    4151        { 
    42                 // Time now 
     52                RunHousekeepingIfNeeded(); 
     53 
     54                // Calculate how long should wait before doing the next housekeeping run 
    4355                int64_t timeNow = GetCurrentBoxTime(); 
    44                 // Do housekeeping if the time interval has elapsed since the last check 
    45                 if((timeNow - lastHousekeepingRun) >= housekeepingInterval) 
    46                 { 
    47                         // Store the time 
    48                         lastHousekeepingRun = timeNow; 
    49                         ::syslog(LOG_INFO, "Starting housekeeping"); 
    50  
    51                         // Get the list of accounts 
    52                         std::vector<int32_t> accounts; 
    53                         if(mpAccountDatabase) 
    54                         { 
    55                                 mpAccountDatabase->GetAllAccountIDs(accounts); 
    56                         } 
    57                          
    58                         SetProcessTitle("housekeeping, active"); 
    59                          
    60                         // Check them all 
    61                         for(std::vector<int32_t>::const_iterator i = accounts.begin(); i != accounts.end(); ++i) 
    62                         { 
    63                                 try 
    64                                 { 
    65                                         if(mpAccounts) 
    66                                         { 
    67                                                 // Get the account root 
    68                                                 std::string rootDir; 
    69                                                 int discSet = 0; 
    70                                                 mpAccounts->GetAccountRoot(*i, rootDir, discSet); 
    71                                                  
    72                                                 // Do housekeeping on this account 
    73                                                 HousekeepStoreAccount housekeeping(*i, rootDir, discSet, *this); 
    74                                                 housekeeping.DoHousekeeping(); 
    75                                         } 
    76                                 } 
    77                                 catch(BoxException &e) 
    78                                 { 
    79                                         ::syslog(LOG_ERR, "while housekeeping account %08X, exception %s (%d/%d) -- aborting housekeeping run for this account", 
    80                                                 *i, e.what(), e.GetType(), e.GetSubType()); 
    81                                 } 
    82                                 catch(std::exception &e) 
    83                                 { 
    84                                         ::syslog(LOG_ERR, "while housekeeping account %08X, exception %s -- aborting housekeeping run for this account", 
    85                                                 *i, e.what()); 
    86                                 } 
    87                                 catch(...) 
    88                                 { 
    89                                         ::syslog(LOG_ERR, "while housekeeping account %08X, unknown exception -- aborting housekeeping run for this account", 
    90                                                 *i); 
    91                                 } 
    92                                  
    93                                 // Check to see if there's any message pending 
    94                                 CheckForInterProcessMsg(0 /* no account */); 
    95                  
    96                                 // Stop early? 
    97                                 if(StopRun()) 
    98                                 { 
    99                                         break; 
    100                                 } 
    101                         } 
    102                          
    103                         ::syslog(LOG_INFO, "Finished housekeeping"); 
    104                 } 
    105  
    106                 // Placed here for accuracy, if StopRun() is true, for example. 
    107                 SetProcessTitle("housekeeping, idle"); 
    108                  
    109                 // Calculate how long should wait before doing the next housekeeping run 
    110                 timeNow = GetCurrentBoxTime(); 
    111                 time_t secondsToGo = BoxTimeToSeconds((lastHousekeepingRun + housekeepingInterval) - timeNow); 
     56                time_t secondsToGo = BoxTimeToSeconds((mLastHousekeepingRun + housekeepingInterval) - timeNow); 
    11257                if(secondsToGo < 1) secondsToGo = 1; 
    11358                if(secondsToGo > 60) secondsToGo = 60; 
     
    11863        } 
    11964} 
    120  
     65#endif 
     66 
     67void BackupStoreDaemon::RunHousekeepingIfNeeded() 
     68{ 
     69        // Get the time between housekeeping runs 
     70        const Configuration &rconfig(GetConfiguration()); 
     71        int64_t housekeepingInterval = SecondsToBoxTime(rconfig.GetKeyValueInt("TimeBetweenHousekeeping")); 
     72 
     73        // Time now 
     74        int64_t timeNow = GetCurrentBoxTime(); 
     75        // Do housekeeping if the time interval has elapsed since the last check 
     76        if((timeNow - mLastHousekeepingRun) < housekeepingInterval) 
     77        { 
     78                return; 
     79        } 
     80 
     81        // Store the time 
     82        mLastHousekeepingRun = timeNow; 
     83        ::syslog(LOG_INFO, "Starting housekeeping"); 
     84 
     85        // Get the list of accounts 
     86        std::vector<int32_t> accounts; 
     87        if(mpAccountDatabase) 
     88        { 
     89                mpAccountDatabase->GetAllAccountIDs(accounts); 
     90        } 
     91                         
     92        SetProcessTitle("housekeeping, active"); 
     93                         
     94        // Check them all 
     95        for(std::vector<int32_t>::const_iterator i = accounts.begin(); i != accounts.end(); ++i) 
     96        { 
     97                try 
     98                { 
     99                        if(mpAccounts) 
     100                        { 
     101                                // Get the account root 
     102                                std::string rootDir; 
     103                                int discSet = 0; 
     104                                mpAccounts->GetAccountRoot(*i, rootDir, discSet); 
     105                                 
     106                                // Do housekeeping on this account 
     107                                HousekeepStoreAccount housekeeping(*i, rootDir, discSet, *this); 
     108                                housekeeping.DoHousekeeping(); 
     109                        } 
     110                } 
     111                catch(BoxException &e) 
     112                { 
     113                        ::syslog(LOG_ERR, "while housekeeping account %08X, exception %s (%d/%d) -- aborting housekeeping run for this account", 
     114                                *i, e.what(), e.GetType(), e.GetSubType()); 
     115                } 
     116                catch(std::exception &e) 
     117                { 
     118                        ::syslog(LOG_ERR, "while housekeeping account %08X, exception %s -- aborting housekeeping run for this account", 
     119                                *i, e.what()); 
     120                } 
     121                catch(...) 
     122                { 
     123                        ::syslog(LOG_ERR, "while housekeeping account %08X, unknown exception -- aborting housekeeping run for this account", 
     124                                *i); 
     125                } 
     126         
     127#ifndef WIN32    
     128                // Check to see if there's any message pending 
     129                CheckForInterProcessMsg(0 /* no account */); 
     130#endif 
     131 
     132                // Stop early? 
     133                if(StopRun()) 
     134                { 
     135                        break; 
     136                } 
     137        } 
     138                 
     139        ::syslog(LOG_INFO, "Finished housekeeping"); 
     140 
     141        // Placed here for accuracy, if StopRun() is true, for example. 
     142        SetProcessTitle("housekeeping, idle"); 
     143} 
     144 
     145#ifdef WIN32 
     146void BackupStoreDaemon::OnIdle() 
     147{ 
     148        if (!mHousekeepingInited) 
     149        { 
     150                HousekeepingInit(); 
     151                mHousekeepingInited = true; 
     152        } 
     153 
     154        RunHousekeepingIfNeeded(); 
     155} 
     156#endif 
    121157 
    122158// -------------------------------------------------------------------------- 
     
    129165// 
    130166// -------------------------------------------------------------------------- 
     167#ifndef WIN32 
    131168bool BackupStoreDaemon::CheckForInterProcessMsg(int AccountNum, int MaximumWaitTime) 
    132169{ 
     
    172209        return false; 
    173210} 
    174  
    175  
     211#endif 
     212 
     213 
  • box/chris/merge/bin/bbstored/BackupCommands.cpp

    r341 r710  
    1010#include "Box.h" 
    1111 
     12#ifdef HAVE_SYSLOG_H 
    1213#include <syslog.h> 
     14#endif 
     15 
     16#include <set> 
     17#include <sstream> 
    1318 
    1419#include "autogen_BackupProtocolServer.h" 
     
    328333                         
    329334                        // Choose a temporary filename for the result of the combination 
    330                         std::string tempFn(RaidFileController::DiscSetPathToFileSystemPath(rContext.GetStoreDiscSet(), rContext.GetStoreRoot() + ".recombinetemp", 
    331                                 p + 16 /* rotate which disc it's on */)); 
     335#ifdef WIN32 
     336                        std::ostringstream fs(rContext.GetStoreRoot()); 
     337                        fs << ".recombinetemp."; 
     338                        fs << p; 
     339                        std::string tempFn(fs.str()); 
     340                        tempFn = RaidFileController::DiscSetPathToFileSystemPath(rContext.GetStoreDiscSet(), tempFn, p + 16); 
     341#else 
     342                        std::string tempFn(RaidFileController::DiscSetPathToFileSystemPath(rContext.GetStoreDiscSet(), rContext.GetStoreRoot() + ".recombinetemp", p + 16 /* rotate which disc it's on */)); 
     343#endif 
    332344                         
    333345                        // Open the temporary file 
     
    337349                                { 
    338350                                        // Write nastily to allow this to work with gcc 2.x 
     351#ifdef WIN32 
     352                                        combined.reset(new FileStream( 
     353                                                tempFn.c_str(),  
     354                                                O_RDWR | O_CREAT | O_EXCL |  
     355                                                O_BINARY | O_TRUNC)); 
     356#else 
    339357                                        std::auto_ptr<IOStream> t(new FileStream(tempFn.c_str(), O_RDWR | O_CREAT | O_EXCL)); 
    340358                                        combined = t; 
     359#endif 
    341360                                } 
     361#ifndef WIN32 
    342362                                // Unlink immediately as it's a temporary file 
    343363                                if(::unlink(tempFn.c_str()) != 0) 
     
    345365                                        THROW_EXCEPTION(CommonException, OSFileError); 
    346366                                } 
     367#endif 
    347368                        } 
    348369                        catch(...) 
     
    360381                         
    361382                        // Then shuffle round for the next go 
     383#ifdef WIN32 
     384                        if (from.get()) from->Close(); 
     385#endif 
    362386                        from = combined; 
    363387                } 
     
    397421                } 
    398422 
    399                 // Object will be deleted when the stream is deleted, so can release the object auto_ptr here to 
    400                 // avoid premature deletiong 
     423                // Object will be deleted when the stream is deleted,  
     424                // so can release the object auto_ptr here to avoid  
     425                // premature deletion 
    401426                object.release(); 
    402427        } 
  • box/chris/merge/bin/bbstored/BackupContext.cpp

    r217 r710  
    133133        bool gotLock = mWriteLock.TryAndGetLock(writeLockFile.c_str(), 0600 /* restrictive file permissions */); 
    134134         
     135#ifndef WIN32 
    135136        if(!gotLock) 
    136137        { 
     
    151152                } while(!gotLock && tries > 0); 
    152153        } 
     154#endif 
    153155         
    154156        if(gotLock) 
     
    454456                        { 
    455457                                // Open it twice 
     458#ifdef WIN32 
     459                                FileStream diff(tempFn.c_str(),  
     460                                        O_RDWR | O_CREAT | O_BINARY); 
     461                                FileStream diff2(tempFn.c_str(),  
     462                                        O_RDWR | O_BINARY); 
     463#else 
    456464                                FileStream diff(tempFn.c_str(), O_RDWR | O_CREAT | O_EXCL); 
    457465                                FileStream diff2(tempFn.c_str(), O_RDONLY); 
    458                                 // Unlink it immediately, so it definately goes away 
     466 
     467                                // Unlink it immediately, so it definitely goes away 
    459468                                if(::unlink(tempFn.c_str()) != 0) 
    460469                                { 
    461470                                        THROW_EXCEPTION(CommonException, OSFileError); 
    462471                                } 
     472#endif 
    463473                                 
    464474                                // Stream the incoming diff to this temporary file 
     
    509519                                throw; 
    510520                        } 
     521 
     522#ifdef WIN32 
     523                        // we can't delete the file while it's open, above 
     524                        if(::unlink(tempFn.c_str()) != 0) 
     525                        { 
     526                                THROW_EXCEPTION(CommonException, OSFileError); 
     527                        } 
     528#endif 
    511529                } 
    512530                 
  • box/chris/merge/bin/bbstored/BackupStoreDaemon.cpp

    r457 r710  
    1212#include <stdlib.h> 
    1313#include <stdio.h> 
     14#include <signal.h> 
     15 
     16#ifdef HAVE_SYSLOG_H 
    1417#include <syslog.h> 
    15 #include <signal.h> 
     18#endif 
    1619 
    1720#include "BackupContext.h" 
     
    4043          mHaveForkedHousekeeping(false), 
    4144          mIsHousekeepingProcess(false), 
     45#ifdef WIN32 
     46          mHousekeepingInited(false) 
     47#else 
    4248          mInterProcessComms(mInterProcessCommsSocket) 
     49#endif 
    4350{ 
    4451} 
     
    157164        mExtendedLogging = config.GetKeyValueBool("ExtendedLogging"); 
    158165         
     166#ifndef WIN32    
    159167        // Fork off housekeeping daemon -- must only do this the first time Run() is called 
    160168        if(!mHaveForkedHousekeeping) 
     
    220228        else 
    221229        { 
     230#endif // !WIN32 
    222231                // In server process -- use the base class to do the magic 
    223232                ServerTLS<BOX_PORT_BBSTORED>::Run(); 
    224233                 
     234#ifndef WIN32    
    225235                // Why did it stop? Tell the housekeeping process to do the same 
    226236                if(IsReloadConfigWanted()) 
     
    233243                } 
    234244        } 
     245#endif 
    235246} 
    236247 
     
    298309        ::syslog(LOG_INFO, "Connection statistics for %s: " 
    299310                        "IN=%lld OUT=%lld TOTAL=%lld\n", commonName, 
    300                         s.GetBytesRead(), s.GetBytesWritten(), 
    301                         s.GetBytesRead() + s.GetBytesWritten()); 
    302 } 
     311                        (long long)s.GetBytesRead(),  
     312                        (long long)s.GetBytesWritten(), 
     313                        (long long)s.GetBytesRead() +  
     314                        (long long)s.GetBytesWritten()); 
     315} 
  • box/chris/merge/bin/bbstored/BackupStoreDaemon.h

    r457 r710  
    3939public: 
    4040 
     41#ifndef WIN32 
    4142        // For BackupContext to comminicate with housekeeping process 
    4243        void SendMessageToHousekeepingProcess(const void *Msg, int MsgLen) 
     
    4445                mInterProcessCommsSocket.Write(Msg, MsgLen); 
    4546        } 
     47#endif 
    4648 
    4749protected: 
     
    5860        const ConfigurationVerify *GetConfigVerify() const; 
    5961         
     62#ifndef WIN32    
    6063        // Housekeeping functions 
    6164        void HousekeepingProcess(); 
    6265        bool CheckForInterProcessMsg(int AccountNum = 0, int MaximumWaitTime = 0); 
     66#endif 
    6367 
    6468        void LogConnectionStats(const char *commonName, const SocketStreamTLS &s); 
     
    7175        bool mIsHousekeepingProcess; 
    7276         
     77#ifdef WIN32 
     78        virtual void OnIdle(); 
     79        bool mHousekeepingInited; 
     80#else 
    7381        SocketStream mInterProcessCommsSocket; 
    7482        IOStreamGetLine mInterProcessComms; 
     83#endif 
     84 
     85        void HousekeepingInit(); 
     86        void RunHousekeepingIfNeeded(); 
     87        int64_t mLastHousekeepingRun; 
    7588}; 
    7689 
  • box/chris/merge/bin/bbstored/HousekeepStoreAccount.cpp

    r217 r710  
    226226bool HousekeepStoreAccount::ScanDirectory(int64_t ObjectID) 
    227227{ 
     228#ifndef WIN32 
    228229        if((--mCountUntilNextInterprocessMsgCheck) <= 0) 
    229230        { 
     
    236237                } 
    237238        } 
     239#endif 
    238240 
    239241        // Get the filename 
     
    252254        BackupStoreDirectory dir; 
    253255        dir.ReadFromStream(*dirStream, IOStream::TimeOutInfinite); 
     256        dirStream->Close(); 
    254257         
    255258        // Is it empty? 
     
    486489        for(std::set<DelEn, DelEnCompare>::iterator i(mPotentialDeletions.begin()); i != mPotentialDeletions.end(); ++i) 
    487490        { 
     491#ifndef WIN32 
    488492                if((--mCountUntilNextInterprocessMsgCheck) <= 0) 
    489493                { 
     
    496500                        } 
    497501                } 
     502#endif 
    498503 
    499504                // Load up the directory it's in 
     
    730735                for(std::vector<int64_t>::const_iterator i(mEmptyDirectories.begin()); i != mEmptyDirectories.end(); ++i) 
    731736                { 
     737#ifndef WIN32 
    732738                        if((--mCountUntilNextInterprocessMsgCheck) <= 0) 
    733739                        { 
     
    740746                                } 
    741747                        } 
     748#endif 
    742749 
    743750                        // Do not delete the root directory 
  • box/chris/merge/configure.ac

    r626 r710  
    4545 
    4646## Check for Berkely DB. Restrict to certain versions 
    47 AX_PATH_BDB(, [ 
     47AX_PATH_BDB([1.x or 4.1], [ 
    4848  LIBS="$BDB_LIBS $LIBS" 
    4949  LDFLAGS="$BDB_LDFLAGS $LDFLAGS" 
     
    9090AC_CHECK_HEADERS([netinet/in.h]) 
    9191AC_CHECK_HEADERS([sys/param.h sys/socket.h sys/time.h sys/types.h sys/wait.h]) 
    92 AC_CHECK_HEADERS([sys/xattr.h]) 
     92AC_CHECK_HEADERS([sys/uio.h sys/xattr.h]) 
    9393 
    9494if test "$ac_cv_header_regex_h" = "yes"; then 
     
    117117AC_CHECK_DECLS([INFTIM],,, [[#include <poll.h>]]) 
    118118AC_CHECK_DECLS([SO_PEERCRED],,, [[#include <sys/socket.h>]]) 
     119AC_CHECK_DECLS([O_BINARY],,,) 
    119120AC_HEADER_TIME 
    120121AC_STRUCT_TM 
     
    125126  AX_BSWAP64 
    126127fi 
     128 
    127129if test "$target_os" != "mingw32"; then 
    128130  AX_RANDOM_DEVICE 
    129 fi 
    130 AX_CHECK_MOUNT_POINT(,[ 
    131   if test "$target_os" != "mingw32" -a "$target_os" != "winnt"; then 
     131  AX_CHECK_MOUNT_POINT(,[ 
    132132    AC_MSG_ERROR([[cannot work out how to discover mount points on your platform]]) 
    133   fi 
    134133  ]) 
     134fi 
     135 
    135136AX_CHECK_MALLOC_WORKAROUND 
    136137 
     
    221222                   runtest.pl 
    222223                   test/backupstorefix/testfiles/testbackupstorefix.pl 
     224                   test/bbackupd/testfiles/bbackupd.conf 
    223225                   test/bbackupd/testfiles/extcheck1.pl 
    224226                   test/bbackupd/testfiles/extcheck2.pl 
     
    238240to the documentation for more information on each feature. 
    239241 
     242Regular expressions: $ac_cv_header_regex_h 
    240243Large files:         $have_large_file_support 
    241244Berkeley DB:         $ax_path_bdb_ok 
  • box/chris/merge/docs/backup/win32_build_on_linux_using_mingw.txt

    r217 r710  
    77- Fedora and SuSE users can download RPM packages from  
    88  [http://mirzam.it.vu.nl/mingw/] 
     9 
     10You will need to know the prefix used by the cross-compiler executables. 
     11It will usually be something like "ix86-mingw32*-". All the binaries in the 
     12cross-compiler package will start with this prefix. The documentation below 
     13assumes that it is "i386-mingw32-". Adjust to taste. 
    914 
    1015Download Zlib from [http://www.zlib.net/], unpack and enter source directory: 
     
    1722        make install prefix=/usr/local/i386-mingw32 
    1823 
    19 Download OpenSSL 0.9.7 from  
     24Download OpenSSL 0.9.8b from  
     25[http://www.openssl.org/source/openssl-0.9.8b.tar.gz] 
     26 
     27Unpack and configure: 
     28 
     29        tar xzvf openssl-0.9.8b.tar.gz 
     30        cd openssl-0.9.8b 
     31        ./Configure mingw 
     32        make makefile.one 
     33        wget http://bbdev.fluffy.co.uk/svn/box/chris/win32/support/openssl-0.9.8b-mingw-cross.patch 
     34        patch -p1 < openssl-0.9.8b-mingw-cross.patch 
     35        make -f makefile.one 
    2036 
    2137Configure Box with: 
     
    2844        export LDFLAGS="-mthreads" 
    2945        export LIBS="-lcrypto -lws2_32 -lgdi32" 
     46        (if you don't have a "configure" file, run "./bootstrap") 
    3047        ./configure --target=i386-mingw32 
    31         make CXX="$CXX" AR="$AR" RANLIB="$RANLIB" 
     48        make CXX="$CXX" AR="$AR" RANLIB="$RANLIB" WINDRES="i386-mingw32-windres" 
  • box/chris/merge/infrastructure/BoxPlatform.pm.in

    r492 r710  
    22use Exporter; 
    33@ISA = qw/Exporter/; 
    4 @EXPORT = qw/$build_os $build_cpu $target_os $make_command $bsd_make $platform_define $platform_cpu $gcc_v3 $product_version $product_name $install_into_dir $sub_make_options $platform_compile_line_extra $platform_link_line_extra $platform_lib_files $platform_exe_ext/; 
     4@EXPORT = qw/$build_os $build_cpu $target_os $make_command $bsd_make $platform_define $platform_cpu $gcc_v3 $product_version $product_name $install_into_dir $sub_make_options $platform_compile_line_extra $platform_link_line_extra $platform_lib_files $platform_exe_ext $target_windows update_if_changed/; 
    55 
    66BEGIN 
     
    88 
    99        # which OS are we building under? 
    10         $build_os = `uname`; 
    11         chomp $build_os; 
    12         $build_cpu = `uname -p`; 
    13         chomp $build_cpu; 
     10        $target_os = '@target_os@'; 
     11        $target_windows = 0; 
     12        $target_windows = 1 if $target_os =~ m'^mingw32'  
     13                or $target_os eq "winnt"; 
     14 
     15        if ($^O eq "MSWin32" and not -x "/usr/bin/uname") 
     16        { 
     17                $build_os = "winnt"; 
     18                $build_cpu = "ix86"; 
     19        } 
     20        else 
     21        { 
     22                $build_os = `uname`; 
     23                chomp $build_os; 
     24                $build_cpu = `uname -m`; 
     25                chomp $build_cpu; 
     26        } 
     27 
    1428        # Cygwin Builds usually something like CYGWIN_NT-5.0, CYGWIN_NT-5.1 
    1529        # Box Backup tried on Win2000,XP only :) 
     
    2539        $platform_link_line_extra = '@LDFLAGS@'; 
    2640        $platform_lib_files = '@LIBS@'; 
    27         $target_os = '@target_os@'; 
    2841        $platform_exe_ext = '@EXEEXT@'; 
    2942 
    3043        # get version 
    31         open VERSION,"VERSION.txt" or die "VERSION.txt: $!"; 
     44        if (! -r "VERSION.txt" and -r "../../VERSION.txt") 
     45        { 
     46                open VERSION,"../../VERSION.txt" or die "../../VERSION.txt: $!"; 
     47        } 
     48        else 
     49        { 
     50                open VERSION,"VERSION.txt" or die "VERSION.txt: $!"; 
     51        } 
     52 
    3253        $product_version = <VERSION>; 
    3354        chomp $product_version; 
     
    90111} 
    91112 
     113sub update_if_changed ($) 
     114{ 
     115        my ($file) = @_; 
     116        die "$file.new: not found" unless -r "$file.new"; 
     117 
     118        if (-r $file) 
     119        { 
     120                die "$file.new: not found" unless -r "$file.new"; 
     121                if (system("diff --brief $file $file.new") == 0) 
     122                { 
     123                        unlink "$file.new"; 
     124                        return; 
     125                } 
     126        } 
     127 
     128        if (system("cp $file.new $file") != 0) 
     129        { 
     130                die "failed to copy $file.new to $file"; 
     131        } 
     132 
     133        if (system("diff --brief $file $file.new") != 0) 
     134        { 
     135                die "$file and $file.new are still different"; 
     136        } 
     137 
     138        unlink "$file.new"; 
     139        return; 
     140} 
     141 
    921421; 
    93143 
  • box/chris/merge/infrastructure/buildenv-testmain-template.cpp

    r219 r710  
    4242 
    4343int failures = 0; 
     44int first_fail_line; 
     45std::string first_fail_file; 
    4446 
    4547int filedes_open_at_beginning = -1; 
     
    129131                        if(failures > 0) 
    130132                        { 
    131                                 printf("FAILED: %d tests failed\n", failures); 
     133                                printf("FAILED: %d tests failed (first at " 
     134                                        "%s:%d)\n", failures,  
     135                                        first_fail_file.c_str(), 
     136                                        first_fail_line); 
    132137                        } 
    133138                        else 
  • box/chris/merge/infrastructure/makebuildenv.pl.in

    r538 r710  
    1515print "Box build environment setup.\n\n"; 
    1616 
    17  
    18 my $implicit_dep = 'lib/common'; 
     17my @implicit_deps = ('lib/common'); 
    1918 
    2019# work out platform variables 
     
    3938my %env_flags; 
    4039 
    41 my $windows_include_path = "-I../../lib/win32 "; 
    42 if ($target_os ne "mingw32" && $target_os ne "winnt") 
    43 { 
    44         $windows_include_path = ""; 
    45         $env_flags{'IGNORE_lib/win32'} = 1; 
     40my $windows_include_path = ""; 
     41if ($target_windows) 
     42{ 
     43        $module_dependency{"lib/common"} = ["lib/win32"]; 
     44        push @implicit_deps, "lib/win32"; 
     45} 
     46else 
     47{ 
     48        # $env_flags{'IGNORE_lib/win32'} = 1; 
    4649} 
    4750 
     
    112115 
    113116 
    114 # open test mail program template file 
     117# open test main program template file 
    115118my $test_template_file = 'infrastructure/buildenv-testmain-template.cpp'; 
    116119open FL,$test_template_file or die "Can't open test template file\n"; 
     
    272275                } 
    273276        } 
    274         $module_dependency{$mod} = [$implicit_dep,@md]; 
     277        $module_dependency{$mod} = [@implicit_deps,@md]; 
    275278        $module_library_link_opts{$mod} = [@lo]; 
    276279         
     
    287290 
    288291# make dirs for implicit dep 
    289 mkdir "release/$implicit_dep",0755; 
    290 mkdir "debug/$implicit_dep",0755; 
     292foreach my $dep (@implicit_deps) 
     293{ 
     294        mkdir "release/$dep",0755; 
     295        mkdir "debug/$dep",0755; 
     296} 
    291297 
    292298# write a list of all the modules we've configured to use 
    293 open CONFIGURED_MODS,'>local/modules.h' or die "Can't write configured modules list"; 
     299open CONFIGURED_MODS,'>local/modules.h.new' or die  
     300        "Can't write configured modules list"; 
    294301print CONFIGURED_MODS <<__E; 
    295302// automatically generated file, do not edit 
     
    297304#define _CONFIGURED_MODULES__H 
    298305__E 
    299 for($implicit_dep,@modules) 
     306for(@implicit_deps,@modules) 
    300307{ 
    301308        my $m = $_; 
     
    307314__E 
    308315close CONFIGURED_MODS; 
    309  
     316update_if_changed("local/modules.h"); 
    310317 
    311318# now make a list of all the .h files we can find, recording which module they're in 
    312319my %hfiles; 
    313 for my $mod (@modules, $implicit_dep) 
     320for my $mod (@modules, @implicit_deps) 
    314321{ 
    315322        opendir DIR,$mod; 
     
    348355} 
    349356 
    350 for my $mod (@modules, $implicit_dep) 
     357for my $mod (@modules, @implicit_deps) 
    351358{ 
    352359        opendir DIR,$mod; 
     
    374381print "done\n\nGenerating Makefiles...\n"; 
    375382 
     383my %module_resources_win32; 
    376384 
    377385# Then write a makefile for each module 
    378 for my $mod (@modules, $implicit_dep) 
     386for my $mod (@implicit_deps, @modules) 
    379387{ 
    380388        print $mod,"\n"; 
     
    387395                my $testmain = $test_template; 
    388396                $testmain =~ s/TEST_NAME/$name/g; 
    389                 open TESTMAIN,">$mod/_main.cpp" or die "Can't open test main file for $mod for writing\n"; 
     397                open TESTMAIN,">$mod/_main.cpp.new" or die  
     398                        "Can't open test main file for $mod for writing\n"; 
    390399                print TESTMAIN $testmain; 
    391400                close TESTMAIN; 
     401                update_if_changed("$mod/_main.cpp"); 
    392402                 
    393403                # test file... 
     
    395405                { 
    396406                        my ($filename,$runcmd,$module) = @_;             
    397                         open TESTFILE,">$filename" or die "Can't open test script file for $module for writing\n"; 
     407                        open TESTFILE,">$filename.new" or die  
     408                                "Can't open test script file for $module " . 
     409                                "for writing\n"; 
    398410                        print TESTFILE "#!/bin/sh\necho TEST: $module\n"; 
    399411                        if(-d "$module/testfiles") 
     
    414426                        print TESTFILE "$runcmd\n"; 
    415427                        close TESTFILE; 
     428                        update_if_changed($filename); 
    416429                } 
    417430                 
    418431                writetestfile("$mod/_t",  
    419                         './test' . $platform_exe_ext . '$1 $2 $3 $4 $5', $mod); 
     432                        './test' . $platform_exe_ext . ' $1 $2 $3 $4 $5', $mod); 
    420433                writetestfile("$mod/_t-gdb",  
    421                         'gdb ./test ' . $platform_exe_ext, $mod); 
     434                        'gdb ./test' . $platform_exe_ext, $mod); 
    422435                 
    423436        } 
     
    442455                # and then dedup and reorder them 
    443456                my %d_done; 
    444                 for(my $a = $#deps_raw; $a >= 0; $a--) 
    445                 { 
    446                         if(!exists $d_done{$deps_raw[$a]}) 
     457                foreach my $dep (reverse @deps_raw) 
     458                { 
     459                        if(!exists $d_done{$dep}) 
    447460                        { 
    448461                                # insert 
    449                                 push @all_deps_for_module, $deps_raw[$a]; 
     462                                push @all_deps_for_module, $dep; 
    450463                                # mark as done 
    451                                 $d_done{$deps_raw[$a]} = 1; 
     464                                $d_done{$dep} = 1; 
    452465                        } 
    453466                } 
     
    481494        # start the makefile 
    482495        my $mk_name_extra = ($bsd_make)?'':'X'; 
    483         open MAKE,">$mod/Makefile".$mk_name_extra or die "Can't open Makefile for $mod\n"; 
     496        open MAKE,">$mod/Makefile".$mk_name_extra.".new" or die  
     497                "Can't open Makefile for $mod\n"; 
    484498        my $debug_link_extra = ($target_is_library)?'':'../../debug/lib/debug/debug.a'; 
    485499 
    486500        my $release_flags = "-O2"; 
    487         if ($target_os eq "mingw32") 
     501        if ($target_windows) 
    488502        { 
    489503                $release_flags = "-O0 -g"; 
     
    500514RANLIB = ranlib 
    501515PERL = "@PERL@" 
     516WINDRES = windres 
    502517.ifdef RELEASE 
    503518CXXFLAGS = -DNDEBUG $release_flags -Wall $include_paths $extra_platform_defines -DBOX_VERSION="\\"$product_version\\"" 
     
    547562        } 
    548563         
    549         # first, obtain a list of depenencies within the .h files 
     564        # first, obtain a list of dependencies within the .h files 
    550565        my %headers; 
    551566        for my $h (grep /\.h\Z/i, @items) 
     
    567582        # then... do the cpp files... 
    568583        my @obj_base; 
    569         for my $cpp (@items) 
    570         { 
    571                 next unless $cpp =~ m/\A(.+)\.cpp\Z/i; 
    572                 next if $cpp =~ /\A\._/;        # Temp Mac OS Resource hack 
     584        for my $file (@items) 
     585        { 
     586                my $is_cpp = $file =~ m/\A(.+)\.cpp\Z/i; 
     587                my $is_rc  = $file =~ m/\A(.+)\.rc\Z/i; 
     588                my $base = $1; 
     589 
     590                if ($target_windows) 
     591                { 
     592                        next if not $is_cpp and not $is_rc; 
     593                } 
     594                else 
     595                { 
     596                        next if not $is_cpp; 
     597                } 
     598 
     599                next if $file =~ /\A\._/; # Temp Mac OS Resource hack 
    573600 
    574601                # store for later 
    575                 my $base = $1; 
    576602                push @obj_base,$base; 
    577603         
    578604                # get the file... 
    579                 open FL,"$mod/$cpp"; 
     605                open FL,"$mod/$file"; 
    580606                my $f; 
    581                 read FL,$f,-s "$mod/$cpp"; 
     607                read FL,$f,-s "$mod/$file"; 
    582608                close FL; 
    583609                 
     
    593619                 
    594620                # write the line for this cpp file 
    595                 $make .= $out_name.': '.join(' ',$cpp,map 
    596                         { ($hfiles{$_} eq $mod)?$_:'../../'.$hfiles{$_}."/$_" } keys %dep)."\n"; 
    597                 $make .= "\t\$(CXX) \$(CXXFLAGS) $compile_line_extra -c $cpp -o $out_name\n\n"; 
    598  
     621                my @dep_paths = map  
     622                {  
     623                        ($hfiles{$_} eq $mod) 
     624                        ? $_  
     625                        : '../../'.$hfiles{$_}."/$_" 
     626                } 
     627                keys %dep; 
     628 
     629                $make .= $out_name.': '.join(' ',$file,@dep_paths)."\n"; 
     630 
     631                if ($is_cpp) 
     632                { 
     633                        $make .= "\t\$(CXX) \$(CXXFLAGS) $compile_line_extra ". 
     634                                "-c $file -o $out_name\n\n"; 
     635                } 
     636                elsif ($is_rc) 
     637                { 
     638                        $make .= "\t\$(WINDRES) $file $out_name\n\n"; 
     639                        my $res_list = $module_resources_win32{$mod}; 
     640                        $res_list ||= []; 
     641                        push @$res_list, $base.'.o'; 
     642                        $module_resources_win32{$mod} = $res_list; 
     643                } 
    599644        } 
    600645 
     
    648693 
    649694        my $o_file_list = join(' ',map {'$(OUTDIR)/'.$_.'.o'} @objs); 
     695 
     696        if ($has_deps and not $bsd_make) 
     697        { 
     698                print MAKE ".PHONY: all\n" . 
     699                        "all: dep_modules $end_target\n\n"; 
     700        } 
     701 
    650702        print MAKE $end_target,': ',$o_file_list; 
    651         print MAKE ' dep_modules' if $has_deps and not $bsd_make; 
    652703        print MAKE " ",$lib_files unless $target_is_library; 
    653704        print MAKE "\n"; 
    654705         
     706        if ($target_windows) 
     707        { 
     708                foreach my $dep (@all_deps_for_module) 
     709                { 
     710                        my $res_list = $module_resources_win32{$dep}; 
     711                        next unless $res_list; 
     712                        $o_file_list .= ' '.join(' ',  
     713                                map {'$(OUTBASE)/'.$dep."/$_"} @$res_list); 
     714                } 
     715        } 
     716 
    655717        # stuff to make the final target... 
    656718        if($target_is_library) 
     
    731793        { 
    732794                # need to post process this into a GNU makefile 
    733                 open MAKE,">$mod/Makefile"; 
    734                 open MAKEB,"$mod/MakefileX"; 
     795                open MAKE,">$mod/Makefile.new" or die $!; 
     796                open MAKEB,"$mod/MakefileX.new" or die $!; 
    735797 
    736798                while(<MAKEB>) 
     
    744806                close MAKEB; 
    745807                close MAKE; 
    746                 unlink "$mod/MakefileX"; 
    747         } 
     808                unlink "$mod/MakefileX.new"; 
     809        } 
     810 
     811        update_if_changed("$mod/Makefile"); 
    748812} 
    749813 
  • box/chris/merge/lib/backupclient/BackupClientFileAttributes.cpp

    r464 r710  
    643643         
    644644        // If working as root, set user IDs 
     645        #ifndef WIN32 
    645646        if(::geteuid() == 0) 
    646647        { 
     
    662663                #endif 
    663664        } 
     665        #endif 
    664666 
    665667        if(static_cast<int>(xattrOffset+sizeof(u_int32_t))<=mpClearAttributes->GetSize()) 
  • box/chris/merge/lib/backupclient/BackupStoreFile.cpp

    r456 r710  
    290290                        stream->CopyStreamTo(out); 
    291291                } 
     292 
     293                out.Close(); 
    292294                 
    293295                // Write the attributes 
  • box/chris/merge/lib/backupclient/BackupStoreObjectDump.cpp

    r456 r710  
    114114                // Output item 
    115115                int16_t f = (*i)->GetFlags(); 
    116                 OutputLine(file, ToTrace, "%06llx %4lld %016llx %4d %3d %4d%s%s%s%s%s%s\n", 
     116#ifdef WIN32 
     117                OutputLine(file, ToTrace,  
     118                        "%06I64x %4I64d %016I64x %4d %3d %4d%s%s%s%s%s%s\n", 
     119#else 
     120                OutputLine(file, ToTrace,  
     121                        "%06llx %4lld %016llx %4d %3d %4d%s%s%s%s%s%s\n", 
     122#endif 
    117123                        (*i)->GetObjectID(), 
    118124                        (*i)->GetSizeInBlocks(), 
  • box/chris/merge/lib/backupstore/BackupStoreAccounts.cpp

    r217 r710  
    142142{ 
    143143        char accid[64]; // big enough! 
    144         ::sprintf(accid, "%08x/", ID); 
    145         return std::string(std::string(BOX_RAIDFILE_ROOT_BBSTORED DIRECTORY_SEPARATOR) + accid); 
     144        ::sprintf(accid, "%08x" DIRECTORY_SEPARATOR, ID); 
     145        return std::string(std::string(BOX_RAIDFILE_ROOT_BBSTORED  
     146                DIRECTORY_SEPARATOR) + accid); 
    146147} 
    147148 
  • box/chris/merge/lib/backupstore/BackupStoreCheck.cpp

    r217 r710  
    329329        StoreStructure::MakeObjectFilename(StartID, mStoreRoot, mDiscSetNumber, dirName, false /* don't make sure the dir exists */); 
    330330        // Check expectations 
    331         ASSERT(dirName.size() > 4 && dirName[dirName.size() - 4] == '/'); 
     331        ASSERT(dirName.size() > 4 &&  
     332                dirName[dirName.size() - 4] == DIRECTORY_SEPARATOR_ASCHAR); 
    332333        // Remove the filename from it 
    333334        dirName.resize(dirName.size() - 4); // four chars for "/o00" 
     
    378379                { 
    379380                        // Unexpected or bad file, delete it 
    380                         ::printf("Spurious file %s/%s found%s\n", dirName.c_str(), (*i).c_str(), mFixErrors?", deleting":""); 
     381                        ::printf("Spurious file %s" DIRECTORY_SEPARATOR "%s " 
     382                                "found%s\n", dirName.c_str(), (*i).c_str(),  
     383                                mFixErrors?", deleting":""); 
    381384                        ++mNumberErrorsFound; 
    382385                        if(mFixErrors) 
  • box/chris/merge/lib/common/BoxPlatform.h

    r483 r710  
    4141#endif 
    4242 
    43 // Slight hack; disable interception on Darwin within raidfile test 
    44 #ifdef __APPLE__ 
     43// Slight hack; disable interception in raidfile test on Darwin and Windows 
     44#if defined __APPLE__ || defined WIN32 
    4545        // TODO: Replace with autoconf test 
    4646        #define PLATFORM_CLIB_FNS_INTERCEPTION_IMPOSSIBLE 
     
    139139#endif 
    140140 
     141// for Unix compatibility with Windows :-) 
     142#if !HAVE_DECL_O_BINARY 
     143        #define O_BINARY 0 
     144#endif 
     145 
    141146#ifdef WIN32 
    142147        typedef u_int64_t InodeRefType; 
  • box/chris/merge/lib/common/FdGetLine.h

    r217 r710  
    1515#ifdef NDEBUG 
    1616        #define FDGETLINE_BUFFER_SIZE           1024 
     17#elif defined WIN32 
     18        // need enough space for at least one unicode character  
     19        // in UTF-8 when calling console_read() from bbackupquery 
     20        #define FDGETLINE_BUFFER_SIZE           5 
    1721#else 
    1822        #define FDGETLINE_BUFFER_SIZE           4 
  • box/chris/merge/lib/common/Guards.h

    r456 r710  
    2525#include "MemLeakFindOn.h" 
    2626 
    27 template <int flags = O_RDONLY, int mode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)> 
     27template <int flags = O_RDONLY | O_BINARY, int mode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)> 
    2828class FileHandleGuard 
    2929{ 
  • box/chris/merge/lib/common/UnixUser.cpp

    r456 r710  
    7676UnixUser::~UnixUser() 
    7777{ 
     78#ifndef WIN32 
    7879        if(mRevertOnDestruction) 
    7980        { 
     
    8586                } 
    8687        } 
     88#endif 
    8789} 
    8890 
     
    99101void UnixUser::ChangeProcessUser(bool Temporary) 
    100102{ 
     103#ifndef WIN32 
    101104        if(Temporary) 
    102105        { 
     
    120123                } 
    121124        } 
     125#endif 
    122126} 
    123127 
  • box/chris/merge/lib/common/makeexception.pl.in

    r537 r710  
    11#!@PERL@ 
     2 
     3use lib "../../infrastructure"; 
     4use BoxPlatform; 
    25 
    36# global exception list file 
    47my $global_list = '../../ExceptionCodes.txt'; 
    5  
    68 
    79my @exception; 
     
    4749print "Generating $class exception...\n"; 
    4850 
    49 open CPP,">autogen_${class}Exception.cpp" or die "Can't open cpp file for writing"; 
    50 open H,">autogen_${class}Exception.h" or die "Can't open h file for writing"; 
     51open CPP,">autogen_${class}Exception.cpp.new" or die "Can't open cpp file for writing"; 
     52open H,">autogen_${class}Exception.h.new" or die "Can't open h file for writing"; 
    5153 
    5254# write header file 
     
    200202close H; 
    201203close CPP; 
     204 
     205update_if_changed("autogen_${class}Exception.cpp"); 
     206update_if_changed("autogen_${class}Exception.h"); 
    202207 
    203208# update the global exception list 
  • box/chris/merge/lib/raidfile/RaidFileRead.cpp

    r217 r710  
    1515#include <errno.h> 
    1616#include <sys/stat.h> 
     17 
     18#ifdef HAVE_SYS_UIO_H 
    1719#include <sys/uio.h> 
     20#endif 
     21 
     22#ifdef HAVE_SYSLOG_H 
    1823#include <syslog.h> 
     24#endif 
     25 
    1926#include <stdarg.h> 
     27 
     28#ifdef HAVE_DIRENT_H 
    2029#include <dirent.h> 
     30#endif 
    2131 
    2232#include <stdio.h> 
     
    584594        // Open the parity file 
    585595        std::string parityFilename(RaidFileUtil::MakeRaidComponentName(rdiscSet, mFilename, (2 + startDisc) % READ_NUMBER_DISCS_REQUIRED)); 
    586         mParityHandle = ::open(parityFilename.c_str(), O_RDONLY, 0555); 
     596        mParityHandle = ::open(parityFilename.c_str(),  
     597                O_RDONLY | O_BINARY, 0555); 
    587598        if(mParityHandle == -1) 
    588599        { 
     
    10181029 
    10191030                // Attempt to open 
    1020                 int osFileHandle = ::open(writeFilename.c_str(), O_RDONLY, 0); 
     1031                int osFileHandle = ::open(writeFilename.c_str(),  
     1032                        O_RDONLY | O_BINARY, 0); 
    10211033                if(osFileHandle == -1) 
    10221034                { 
     
    10561068                { 
    10571069                        // Open stripe1 
    1058                         stripe1 = ::open(stripe1Filename.c_str(), O_RDONLY, 0555); 
     1070                        stripe1 = ::open(stripe1Filename.c_str(),  
     1071                                O_RDONLY | O_BINARY, 0555); 
    10591072                        if(stripe1 == -1) 
    10601073                        { 
     
    10621075                        } 
    10631076                        // Open stripe2 
    1064                         stripe2 = ::open(stripe2Filename.c_str(), O_RDONLY, 0555); 
     1077                        stripe2 = ::open(stripe2Filename.c_str(),  
     1078                                O_RDONLY | O_BINARY, 0555); 
    10651079                        if(stripe2 == -1) 
    10661080                        { 
     
    11701184                        if(existingFiles & RaidFileUtil::Stripe1Exists) 
    11711185                        { 
    1172                                 stripe1 = ::open(stripe1Filename.c_str(), O_RDONLY, 0555); 
     1186                                stripe1 = ::open(stripe1Filename.c_str(),  
     1187                                        O_RDONLY | O_BINARY, 0555); 
    11731188                                if(stripe1 == -1) 
    11741189                                { 
     
    11791194                        if(existingFiles & RaidFileUtil::Stripe2Exists) 
    11801195                        { 
    1181                                 stripe2 = ::open(stripe2Filename.c_str(), O_RDONLY, 0555); 
     1196                                stripe2 = ::open(stripe2Filename.c_str(),  
     1197                                        O_RDONLY | O_BINARY, 0555); 
    11821198                                if(stripe2 == -1) 
    11831199                                { 
     
    11861202                        } 
    11871203                        // Open parity 
    1188                         parity = ::open(parityFilename.c_str(), O_RDONLY, 0555); 
     1204                        parity = ::open(parityFilename.c_str(),  
     1205                                O_RDONLY | O_BINARY, 0555); 
    11891206                        if(parity == -1) 
    11901207                        { 
  • box/chris/merge/lib/raidfile/RaidFileWrite.cpp

    r437 r710  
    105105 
    106106        // Attempt to open 
    107         mOSFileHandle = ::open(writeFilename.c_str(), O_WRONLY | O_CREAT, 
     107        mOSFileHandle = ::open(writeFilename.c_str(),  
     108                O_WRONLY | O_CREAT | O_BINARY, 
    108109                S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); 
    109110        if(mOSFileHandle == -1) 
     
    116117        int errnoBlock = EWOULDBLOCK; 
    117118        if(::flock(mOSFileHandle, LOCK_EX | LOCK_NB) != 0) 
    118 #else 
     119#elif HAVE_DECL_F_SETLK 
    119120        int errnoBlock = EAGAIN; 
    120121        struct flock desc; 
     
    124125        desc.l_len = 0; 
    125126        if(::fcntl(mOSFileHandle, F_SETLK, &desc) != 0) 
     127#else 
     128        int errnoBlock = ENOSYS; 
     129        if (0) 
    126130#endif 
    127131        { 
     
    243247         
    244248        // Rename it into place -- BEFORE it's closed so lock remains 
     249 
     250#ifdef WIN32 
     251        // Except on Win32 which doesn't allow renaming open files 
     252        // Close file... 
     253        if(::close(mOSFileHandle) != 0) 
     254        { 
     255                THROW_EXCEPTION(RaidFileException, OSError) 
     256        } 
     257        mOSFileHandle = -1; 
     258#endif // WIN32 
     259 
    245260        RaidFileController &rcontroller(RaidFileController::GetController()); 
    246261        RaidFileDiscSet rdiscSet(rcontroller.GetDiscSet(mSetNumber)); 
     
    249264        // And the current name 
    250265        std::string renameFrom(renameTo + 'X'); 
     266 
     267#ifdef WIN32 
     268        // need to delete the target first 
     269        if(::unlink(renameTo.c_str()) != 0 &&  
     270                GetLastError() != ERROR_FILE_NOT_FOUND) 
     271        { 
     272                THROW_EXCEPTION(RaidFileException, OSError) 
     273        } 
     274#endif 
     275 
    251276        if(::rename(renameFrom.c_str(), renameTo.c_str()) != 0) 
    252277        { 
     
    254279        } 
    255280         
     281#ifndef WIN32    
    256282        // Close file... 
    257283        if(::close(mOSFileHandle) != 0) 
     
    260286        } 
    261287        mOSFileHandle = -1; 
     288#endif // !WIN32 
    262289         
    263290        // Raid it? 
     
    293320         
    294321        // Unlink and close it 
    295         if((::unlink(writeFilename.c_str()) != 0) 
    296                 || (::close(mOSFileHandle) != 0)) 
     322 
     323#ifdef WIN32 
     324        // On Win32 we must close it first 
     325        if (::close(mOSFileHandle) != 0 || 
     326                ::unlink(writeFilename.c_str()) != 0) 
     327#else // !WIN32 
     328        if (::unlink(writeFilename.c_str()) != 0 || 
     329                ::close(mOSFileHandle) != 0) 
     330#endif // !WIN32 
    297331        { 
    298332                THROW_EXCEPTION(RaidFileException, OSError) 
     
    389423        { 
    390424#if HAVE_DECL_O_EXLOCK 
    391                 FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL | O_EXLOCK)> stripe1(stripe1FilenameW.c_str()); 
    392                 FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL | O_EXLOCK)> stripe2(stripe2FilenameW.c_str()); 
    393                 FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL | O_EXLOCK)> parity(parityFilenameW.c_str()); 
     425                FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL | O_EXLOCK | O_BINARY)> stripe1(stripe1FilenameW.c_str()); 
     426                FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL | O_EXLOCK | O_BINARY)> stripe2(stripe2FilenameW.c_str()); 
     427                FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL | O_EXLOCK | O_BINARY)> parity(parityFilenameW.c_str()); 
    394428#else 
    395                 FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL)> stripe1(stripe1FilenameW.c_str()); 
    396                 FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL)> stripe2(stripe2FilenameW.c_str()); 
    397                 FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL)> parity(parityFilenameW.c_str()); 
     429                FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL | O_BINARY)> stripe1(stripe1FilenameW.c_str()); 
     430                FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL | O_BINARY)> stripe2(stripe2FilenameW.c_str()); 
     431                FileHandleGuard<(O_WRONLY | O_CREAT | O_EXCL | O_BINARY)> parity(parityFilenameW.c_str()); 
    398432#endif 
    399433 
     
    531565                stripe2.Close(); 
    532566                stripe1.Close(); 
     567 
     568#ifdef WIN32 
     569                // Must delete before renaming 
     570                #define CHECK_UNLINK(file) \ 
     571                { \ 
     572                        if (::unlink(file) != 0 && errno != ENOENT) \ 
     573                        { \ 
     574                                THROW_EXCEPTION(RaidFileException, OSError); \ 
     575                        } \ 
     576                } 
     577                CHECK_UNLINK(stripe1Filename.c_str()); 
     578                CHECK_UNLINK(stripe2Filename.c_str()); 
     579                CHECK_UNLINK(parityFilename.c_str()); 
     580                #undef CHECK_UNLINK 
     581#endif 
    533582                 
    534583                // Rename them into place 
  • box/chris/merge/lib/server/Daemon.cpp

    r456 r710  
    2222#ifdef HAVE_SYSLOG_H 
    2323        #include <syslog.h> 
     24#endif 
     25 
     26#ifdef WIN32 
     27        #include <ws2tcpip.h> 
    2428#endif 
    2529 
     
    143147                                fprintf(stderr, "%s: failed to start: " 
    144148                                        "failed to open configuration file: " 
    145                                         "%s", DaemonName(),  
     149                                        "%s\n", DaemonName(),  
    146150                                        mConfigFileName.c_str()); 
    147151#ifdef WIN32 
     
    190194                        THROW_EXCEPTION(ServerException, DaemoniseFailed) 
    191195                } 
     196#endif // !WIN32 
    192197                 
    193198                // Server configuration 
     
    198203                pidFileName = serverConfig.GetKeyValue("PidFile"); 
    199204                FileHandleGuard<(O_WRONLY | O_CREAT | O_TRUNC), (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)> pidFile(pidFileName.c_str()); 
    200                  
     205         
     206#ifndef WIN32    
    201207                // Handle changing to a different user 
    202208                if(serverConfig.KeyExists("User")) 
     
    268274                // open the log 
    269275                ::openlog(DaemonName(), LOG_PID, LOG_LOCAL6); 
     276 
    270277                // Log the start message 
    271278                ::syslog(LOG_INFO, "Starting daemon (config: %s) (version "  
    272279                        BOX_VERSION ")", mConfigFileName.c_str()); 
    273280 
    274 #ifndef WIN32 
    275281                // Write PID to file 
    276282                char pid[32]; 
     283 
     284#ifdef WIN32 
     285                int pidsize = sprintf(pid, "%d", (int)GetCurrentProcessId()); 
     286#else 
    277287                int pidsize = sprintf(pid, "%d", (int)getpid()); 
     288#endif 
     289 
    278290                if(::write(pidFile, pid, pidsize) != pidsize) 
    279291                { 
     
    281293                        THROW_EXCEPTION(ServerException, DaemoniseFailed) 
    282294                } 
    283 #endif 
    284295                 
    285296                // Set up memory leak reporting 
     
    353364                return 1; 
    354365        } 
     366 
     367#ifdef WIN32 
     368        // Under win32 we must initialise the Winsock library 
     369        // before using sockets 
     370 
     371        WSADATA info; 
     372 
     373        if (WSAStartup(0x0101, &info) == SOCKET_ERROR) 
     374        { 
     375                // will not run without sockets 
     376                ::syslog(LOG_ERR, "Failed to initialise Windows Sockets"); 
     377                THROW_EXCEPTION(CommonException, Internal) 
     378        } 
     379#endif 
     380 
     381        int retcode = 0; 
    355382         
    356383        // Main Daemon running 
     
    382409                                                errors.c_str()); 
    383410                                        // And give up 
    384                                         return 1; 
     411                                        retcode = 1; 
     412                                        break; 
    385413                                } 
    386414                                 
     
    410438                        "(%d/%d)", DaemonName(), e.what(), e.GetType(),  
    411439                        e.GetSubType()); 
    412                 return 1; 
     440                retcode = 1; 
    413441        } 
    414442        catch(std::exception &e) 
     
    416444                ::syslog(LOG_ERR, "%s: terminating due to exception %s",  
    417445                        DaemonName(), e.what()); 
    418                 return 1; 
     446                retcode = 1; 
    419447        } 
    420448        catch(...) 
     
    422450                ::syslog(LOG_ERR, "%s: terminating due to unknown exception", 
    423451                        DaemonName()); 
    424                 return 1; 
    425         } 
    426          
    427         return 0; 
     452                retcode = 1; 
     453        } 
     454 
     455#ifdef WIN32 
     456        WSACleanup(); 
     457#endif 
     458         
     459        return retcode; 
    428460} 
    429461 
  • box/chris/merge/lib/server/ServerStream.h

    r217 r710  
    5757        } 
    5858 
     59        #ifdef WIN32 
     60        virtual void OnIdle() { } 
     61        #endif 
     62 
    5963        virtual void Run() 
    6064        { 
     
    216220                                        { 
    217221                                                // Since this is a template parameter, the if() will be optimised out by the compiler 
     222                                                #ifndef WIN32 // no fork on Win32 
    218223                                                if(ForkToHandleRequests) 
    219224                                                { 
     
    256261                                                else 
    257262                                                { 
     263                                                #endif // !WIN32 
    258264                                                        // Just handle in this connection 
    259265                                                        SetProcessTitle("handling"); 
    260266                                                        HandleConnection(*connection); 
    261267                                                        SetProcessTitle("idle");                                                                                 
    262                                                 } 
     268                                                #ifndef WIN32 
     269                                                } 
     270                                                #endif // !WIN32 
    263271                                        } 
    264272                                } 
    265                                  
     273 
     274                                #ifdef WIN32 
     275                                OnIdle(); 
     276                                #else // !WIN32 
    266277                                // Clean up child processes (if forking daemon) 
    267278                                if(ForkToHandleRequests) 
     
    278289                                        } while(p > 0); 
    279290                                } 
     291                                #endif // !WIN32 
    280292                        } 
    281293                } 
     
    302314        bool WillForkToHandleRequests() 
    303315        { 
     316                #ifdef WIN32 
     317                return false; 
     318                #else 
    304319                return ForkToHandleRequests; 
     320                #endif // WIN32 
    305321        } 
    306322 
  • box/chris/merge/lib/server/SocketStream.cpp

    r457 r710  
    3737// -------------------------------------------------------------------------- 
    3838SocketStream::SocketStream() 
    39         : mSocketHandle(-1), 
     39        : mSocketHandle(INVALID_SOCKET_VALUE), 
    4040          mReadClosed(false), 
    4141          mWriteClosed(false), 
     
    8686                THROW_EXCEPTION(ServerException, BadSocketHandle); 
    8787        } 
    88         if(mSocketHandle == -1) 
     88        if(mSocketHandle == INVALID_SOCKET_VALUE) 
    8989        { 
    9090                THROW_EXCEPTION(ServerException, DupError); 
     
    102102SocketStream::~SocketStream() 
    103103{ 
    104         if(mSocketHandle != -1) 
     104        if(mSocketHandle != INVALID_SOCKET_VALUE) 
    105105        { 
    106106                Close(); 
     
    118118void SocketStream::Attach(int socket) 
    119119{ 
    120         if(mSocketHandle != -1) {THROW_EXCEPTION(ServerException, SocketAlreadyOpen)} 
     120        if(mSocketHandle != INVALID_SOCKET_VALUE)  
     121        { 
     122                THROW_EXCEPTION(ServerException, SocketAlreadyOpen) 
     123        } 
    121124 
    122125        mSocketHandle = socket; 
     
    135138void SocketStream::Open(int Type, const char *Name, int Port) 
    136139{ 
    137         if(mSocketHandle != -1) {THROW_EXCEPTION(ServerException, SocketAlreadyOpen)} 
     140        if(mSocketHandle != INVALID_SOCKET_VALUE)  
     141        { 
     142                THROW_EXCEPTION(ServerException, SocketAlreadyOpen) 
     143        } 
    138144         
    139145        // Setup parameters based on type, looking up names if required 
     
    145151        // Create the socket 
    146152        mSocketHandle = ::socket(sockDomain, SOCK_STREAM, 0 /* let OS choose protocol */); 
    147         if(mSocketHandle == -1) 
     153        if(mSocketHandle == INVALID_SOCKET_VALUE) 
    148154        { 
    149155                THROW_EXCEPTION(ServerException, SocketOpenError) 
     
    159165                ::close(mSocketHandle); 
    160166#endif 
    161                 mSocketHandle = -1; 
     167                mSocketHandle = INVALID_SOCKET_VALUE; 
    162168                THROW_EXCEPTION(ConnectionException, Conn_SocketConnectError) 
    163169        } 
     
    175181int SocketStream::Read(void *pBuffer, int NBytes, int Timeout) 
    176182{ 
    177         if(mSocketHandle == -1) {THROW_EXCEPTION(ServerException, BadSocketHandle)} 
     183        if(mSocketHandle == INVALID_SOCKET_VALUE)  
     184        { 
     185                THROW_EXCEPTION(ServerException, BadSocketHandle) 
     186        } 
    178187 
    179188        if(Timeout != IOStream::TimeOutInfinite) 
     
    248257void SocketStream::Write(const void *pBuffer, int NBytes) 
    249258{ 
    250         if(mSocketHandle == -1) {THROW_EXCEPTION(ServerException, BadSocketHandle)} 
     259        if(mSocketHandle == INVALID_SOCKET_VALUE)  
     260        { 
     261                THROW_EXCEPTION(ServerException, BadSocketHandle) 
     262        } 
    251263         
    252264        // Buffer in byte sized type. 
     
    312324void SocketStream::Close() 
    313325{ 
    314         if(mSocketHandle == -1) {THROW_EXCEPTION(ServerException, BadSocketHandle)} 
     326        if(mSocketHandle == INVALID_SOCKET_VALUE)  
     327        { 
     328                THROW_EXCEPTION(ServerException, BadSocketHandle) 
     329        } 
    315330#ifdef WIN32 
    316331        if(::closesocket(mSocketHandle) == -1) 
     
    321336                THROW_EXCEPTION(ServerException, SocketCloseError) 
    322337        } 
    323         mSocketHandle = -1; 
     338        mSocketHandle = INVALID_SOCKET_VALUE; 
    324339} 
    325340 
     
    334349void SocketStream::Shutdown(bool Read, bool Write) 
    335350{ 
    336         if(mSocketHandle == -1) {THROW_EXCEPTION(ServerException, BadSocketHandle)} 
     351        if(mSocketHandle == INVALID_SOCKET_VALUE)  
     352        { 
     353                THROW_EXCEPTION(ServerException, BadSocketHandle) 
     354        } 
    337355         
    338356        // Do anything? 
     
    389407tOSSocketHandle SocketStream::GetSocketHandle() 
    390408{ 
    391         if(mSocketHandle == -1) {THROW_EXCEPTION(ServerException, BadSocketHandle)} 
     409        if(mSocketHandle == INVALID_SOCKET_VALUE)  
     410        { 
     411                THROW_EXCEPTION(ServerException, BadSocketHandle) 
     412        } 
    392413        return mSocketHandle; 
    393414} 
  • box/chris/merge/lib/server/SocketStream.h

    r457 r710  
    1515#ifdef WIN32 
    1616        typedef SOCKET tOSSocketHandle; 
     17        #define INVALID_SOCKET_VALUE (tOSSocketHandle)(-1) 
    1718#else 
    1819        typedef int tOSSocketHandle; 
     20        #define INVALID_SOCKET_VALUE -1 
    1921#endif 
    2022 
  • box/chris/merge/lib/server/SocketStreamTLS.cpp

    r457 r710  
    138138        } 
    139139 
    140 #ifndef WIN32 
    141140        // Make the socket non-blocking so timeouts on Read work 
     141 
     142#ifdef WIN32 
     143        u_long nonblocking = 1; 
     144        ioctlsocket(socket, FIONBIO, &nonblocking); 
     145#else // !WIN32 
    142146        // This is more portable than using ioctl with FIONBIO 
    143147        int statusFlags = 0; 
     
    310314                case SSL_ERROR_WANT_READ: 
    311315                case SSL_ERROR_WANT_WRITE: 
    312                         // wait for the requried data 
     316                        // wait for the required data 
    313317                        // Will only get once around this loop, so don't need to calculate timeout values 
    314318                        if(WaitWhenRetryRequired(se, Timeout) == false) 
  • box/chris/merge/lib/server/makeprotocol.pl.in

    r537 r710  
    11#!@PERL@ 
    22use strict; 
     3 
     4use lib "../../infrastructure"; 
     5use BoxPlatform; 
    36 
    47# Make protocol C++ classes from a protocol description file 
     
    168171# open files 
    169172my $h_filename = 'autogen_'.$protocol_name.'Protocol'.$type.'.h'; 
    170 open CPP,'>autogen_'.$protocol_name.'Protocol'.$type.'.cpp'; 
    171 open H,">$h_filename"; 
     173open CPP,'>autogen_'.$protocol_name.'Protocol'.$type.'.cpp.new'; 
     174open H,">$h_filename.new"; 
    172175 
    173176print CPP <<__E; 
     
    913916close CPP; 
    914917 
     918update_if_changed('autogen_'.$protocol_name.'Protocol'.$type.'.cpp'); 
     919update_if_changed($h_filename); 
    915920 
    916921sub obj_is_type 
     
    982987                        # need to translate it 
    983988                        my ($format,$arg) = @{$log_display_types{$ty}}; 
     989                        $arg =~ s/VAR/m$nm/g; 
     990 
     991                        if ($format eq "0x%llx" and $target_windows) 
     992                        { 
     993                                $format = "0x%I64x"; 
     994                                $arg = "(uint64_t)$arg"; 
     995                        } 
     996 
    984997                        push @str,$format; 
    985                         $arg =~ s/VAR/m$nm/g; 
    986998                        push @arg,$arg; 
    987999                } 
  • box/chris/merge/runtest.pl.in

    r537 r710  
    11#!@PERL@ 
     2 
     3use strict; 
     4use warnings; 
    25 
    36use lib 'infrastructure'; 
     
    69my ($test_name,$test_mode) = @ARGV; 
    710 
    8 $test_mode = 'debug' if $test_mode eq ''; 
     11$test_mode = 'debug' if not defined $test_mode or $test_mode eq ''; 
    912 
    1013if($test_name eq '' || ($test_mode ne 'debug' && $test_mode ne 'release')) 
     
    1821 
    1922__E 
    20         exit(0); 
     23        exit(2); 
    2124} 
    2225 
    2326my @results; 
     27my $exit_code = 0; 
    2428 
    2529if($test_name ne 'ALL') 
    2630{ 
    27         # run one test 
    28         runtest($test_name); 
     31        # run one or more specified test 
     32        if ($test_name =~ m/,/) 
     33        { 
     34                foreach my $test (split m/,/, $test_name) 
     35                { 
     36                        runtest($test); 
     37                } 
     38        } 
     39        else 
     40        { 
     41                runtest($test_name); 
     42        } 
    2943} 
    3044else 
     
    5872print "--------\n",join("\n",@results),"\n"; 
    5973 
     74exit $exit_code; 
     75 
    6076sub runtest 
    6177{ 
     
    6884        { 
    6985                push @results,"$t: make failed"; 
     86                $exit_code = 2; 
    7087                return; 
    7188        } 
     
    83100                } 
    84101                close RESULTS; 
     102 
    85103                chomp $last; 
    86104                push @results,"$t: $last"; 
     105 
     106                if ($last ne "PASSED")  
     107                {  
     108                        $exit_code = 1; 
     109                } 
    87110        } 
    88111        else 
  • box/chris/merge/test/backupdiff/testbackupdiff.cpp

    r356 r710  
    6767void make_file_of_zeros(const char *filename, size_t size) 
    6868{ 
    69         static const size_t bs = 0x10000; 
    70         size_t remSize = size; 
    71         void *b = malloc(bs); 
    72         memset(b, 0, bs); 
    73         FILE *f = fopen(filename, "wb"); 
    74  
    75         // Using largish blocks like this is much faster, while not consuming too much RAM 
    76         while(remSize > bs) 
    77         { 
    78                 fwrite(b, bs, 1, f); 
    79                 remSize -= bs; 
    80         } 
    81         fwrite(b, remSize, 1, f); 
    82  
    83         fclose(f); 
    84         free(b); 
     69        #ifdef WIN32 
     70        HANDLE handle = openfile(filename, O_WRONLY | O_CREAT | O_EXCL, 0); 
     71        TEST_THAT(handle != INVALID_HANDLE_VALUE); 
     72        SetFilePointer(handle, size, NULL, FILE_BEGIN); 
     73        TEST_THAT(GetLastError() == NO_ERROR); 
     74        TEST_THAT(SetEndOfFile(handle) == true); 
     75        TEST_THAT(CloseHandle(handle)  == true); 
     76        #else 
     77        int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0600); 
     78        if (fd < 0) perror(filename); 
     79        TEST_THAT(fd >= 0); 
     80        TEST_THAT(ftruncate(fd, size) == 0); 
     81        TEST_THAT(close(fd) == 0); 
     82        #endif 
    8583 
    8684        TEST_THAT((size_t)TestGetFileSize(filename) == size); 
     
    119117                { 
    120118                        nnew++; 
     119                        #ifdef WIN32 
     120                        TRACE2("%8I64d this  s=%8I64d", b, s); 
     121                        #else 
    121122                        TRACE2("%8lld this  s=%8lld", b, s); 
     123                        #endif 
    122124                } 
    123125                else 
    124126                { 
    125127                        nold++; 
     128                        #ifdef WIN32 
     129                        TRACE2("%8I64d other i=%8I64d", b, 0 - s);               
     130                        #else 
    126131                        TRACE2("%8lld other i=%8lld", b, 0 - s);                 
     132                        #endif 
    127133                } 
    128134                // Decode the rest 
     
    208214        else 
    209215        { 
     216#ifdef WIN32 
     217                // Emulate the above stage! 
     218                char src[256], dst[256]; 
     219                sprintf(src, "testfiles\\f%d.diff", to); 
     220                sprintf(dst, "testfiles\\f%d.encoded", to); 
     221                TEST_THAT(CopyFile(src, dst, FALSE) != 0) 
     222#else 
    210223                // Emulate the above stage! 
    211224                char cmd[256]; 
    212225                sprintf(cmd, "cp testfiles/f%d.diff testfiles/f%d.encoded", to, to); 
    213226                ::system(cmd); 
     227#endif 
    214228        } 
    215229 
     
    356370        // Want to trace out all the details 
    357371        #ifndef NDEBUG 
     372        #ifndef WIN32 
    358373        BackupStoreFile::TraceDetailsOfDiffProcess = true; 
     374        #endif 
    359375        #endif 
    360376 
     
    371387                std::auto_ptr<IOStream> encoded(BackupStoreFile::EncodeFile("testfiles/f0", 1 /* dir ID */, f0name)); 
    372388                encoded->CopyStreamTo(out); 
     389                out.Close(); 
    373390                check_encoded_file("testfiles/f0.encoded", 0, 33, 0); 
    374391        } 
     
    431448                        std::auto_ptr<IOStream> encoded(BackupStoreFile::EncodeFile("testfiles/f9", 1 /* dir ID */, fn)); 
    432449                        encoded->CopyStreamTo(out); 
     450                        out.Close(); 
    433451                        check_encoded_file("testfiles/f9.zerotest", 0, 0, 0);            
    434452                } 
     
    441459        } 
    442460         
     461#ifndef WIN32    
    443462        // Check that symlinks aren't diffed 
    444463        TEST_THAT(::symlink("f2", "testfiles/f2.symlink") == 0) 
     
    468487                check_encoded_file("testfiles/f2.symlink.diff", 0, 0, 0);                
    469488        } 
    470  
    471         // Check that diffing against a file which isn't "complete" and referes another isn't allowed 
     489#endif 
     490 
     491        // Check that diffing against a file which isn't "complete" and  
     492        // references another isn't allowed 
    472493        { 
    473494                FileStream blockindex("testfiles/f1.diff"); 
     
    481502        } 
    482503 
    483         // Found a nasty case where files of lots of the same thing sock up lots of processor 
    484         // time -- because of lots of matches found. Check this out! 
     504        // Found a nasty case where files of lots of the same thing  
     505        // suck up lots of processor time -- because of lots of matches  
     506        // found. Check this out! 
     507 
     508        #ifdef WIN32 
     509        ::fprintf(stdout, "Testing diffing two large streams, " 
     510                "may take a while!\n"); 
     511        ::fflush(stdout); 
     512        #endif 
     513 
    485514        make_file_of_zeros("testfiles/zero.0", 20*1024*1024); 
    486515        make_file_of_zeros("testfiles/zero.1", 200*1024*1024); 
     516 
    487517        // Generate a first encoded file 
    488518        { 
     
    504534                        0, 0)); 
    505535                encoded->CopyStreamTo(out); 
     536 
     537                printf("Time taken: %d seconds\n", (int)(time(0) - beginTime)); 
     538 
     539                #ifdef WIN32 
     540                TEST_THAT(time(0) < (beginTime + 300)); 
     541                #else 
    506542                TEST_THAT(time(0) < (beginTime + 40)); 
     543                #endif 
    507544        } 
    508545        // Remove zero-files to save disk space 
  • box/chris/merge/test/backupstore/testbackupstore.cpp

    r341 r710  
    426426         
    427427        free(data); 
    428         unlink("testfiles/test_download"); 
     428        in.Close(); 
     429        TEST_THAT(unlink("testfiles/test_download") == 0); 
    429430} 
    430431 
     
    931932                TEST_THAT(loginConf->GetClientStoreMarker() == 0); 
    932933 
     934#ifndef WIN32 
    933935                // Check that we can't open a new connection which requests write permissions 
    934936                { 
     
    942944                        protocol.QueryFinished(); 
    943945                } 
     946#endif 
    944947                 
    945948                // Set the client store marker 
    946949                protocol.QuerySetClientStoreMarker(0x8732523ab23aLL); 
    947950 
     951#ifndef WIN32 
    948952                // Open a new connection which is read only 
    949953                SocketStreamTLS connReadOnly; 
     
    964968                        TEST_THAT(loginConf->GetClientStoreMarker() == 0x8732523ab23aLL); 
    965969                } 
     970#else // WIN32 
     971                BackupProtocolClient& protocolReadOnly(protocol); 
     972#endif 
    966973 
    967974                test_server_1(protocol, protocolReadOnly); 
    968  
    969  
    970975                // Create and upload some test files 
    971976                int64_t maxID = 0; 
     
    14391444                         
    14401445                // Finish the connections 
     1446#ifndef WIN32 
    14411447                protocolReadOnly.QueryFinished(); 
     1448#endif 
    14421449                protocol.QueryFinished(); 
    14431450                 
    14441451                // Close logs 
     1452#ifndef WIN32 
    14451453                ::fclose(protocolReadOnlyLog); 
     1454#endif 
    14461455                ::fclose(protocolLog); 
    14471456        } 
     
    15211530                // The test block to a file 
    15221531                { 
    1523                         FileStream f("testfiles/testenc1", O_WRONLY | O_CREAT | O_EXCL); 
     1532                        FileStream f("testfiles" DIRECTORY_SEPARATOR  
     1533                                "testenc1", O_WRONLY | O_CREAT | O_EXCL); 
    15241534                        f.Write(encfile, sizeof(encfile)); 
    15251535                } 
     
    15271537                // Encode it 
    15281538                { 
    1529                         FileStream out("testfiles/testenc1_enc", O_WRONLY | O_CREAT | O_EXCL); 
    1530                         BackupStoreFilenameClear name("testfiles/testenc1"); 
    1531  
    1532                         std::auto_ptr<IOStream> encoded(BackupStoreFile::EncodeFile("testfiles/testenc1", 32, name)); 
     1539                        FileStream out("testfiles" DIRECTORY_SEPARATOR  
     1540                                "testenc1_enc", O_WRONLY | O_CREAT | O_EXCL); 
     1541                        BackupStoreFilenameClear name("testfiles" 
     1542                                DIRECTORY_SEPARATOR "testenc1"); 
     1543 
     1544                        std::auto_ptr<IOStream> encoded( 
     1545                                BackupStoreFile::EncodeFile( 
     1546                                        "testfiles" DIRECTORY_SEPARATOR 
     1547                                        "testenc1", 32, name)); 
    15331548                        encoded->CopyStreamTo(out); 
    15341549                } 
     
    15361551                // Verify it 
    15371552                { 
    1538                         FileStream enc("testfiles/testenc1_enc"); 
     1553                        FileStream enc("testfiles" DIRECTORY_SEPARATOR  
     1554                                "testenc1_enc"); 
    15391555                        TEST_THAT(BackupStoreFile::VerifyEncodedFileFormat(enc) == true); 
    15401556                } 
     
    15421558                // Decode it 
    15431559                { 
    1544                         FileStream enc("testfiles/testenc1_enc"); 
    1545                         BackupStoreFile::DecodeFile(enc, "testfiles/testenc1_orig", IOStream::TimeOutInfinite); 
     1560                        FileStream enc("testfiles" DIRECTORY_SEPARATOR  
     1561                                "testenc1_enc"); 
     1562                        BackupStoreFile::DecodeFile(enc, "testfiles" 
     1563                                DIRECTORY_SEPARATOR "testenc1_orig",  
     1564                                IOStream::TimeOutInfinite); 
    15461565                } 
    15471566                 
    15481567                // Read in rebuilt original, and compare contents 
    15491568                { 
    1550                         TEST_THAT(TestGetFileSize("testfiles/testenc1_orig") == sizeof(encfile)); 
    1551                         FileStream in("testfiles/testenc1_orig"); 
     1569                        TEST_THAT(TestGetFileSize("testfiles"  
     1570                                DIRECTORY_SEPARATOR "testenc1_orig")  
     1571                                == sizeof(encfile)); 
     1572                        FileStream in("testfiles" DIRECTORY_SEPARATOR  
     1573                                "testenc1_orig"); 
    15521574                        int encfile_i[ENCFILE_SIZE]; 
    15531575                        in.Read(encfile_i, sizeof(encfile_i)); 
     
    15571579                // Check how many blocks it had, and test the stream based interface 
    15581580                { 
    1559                         FileStream enc("testfiles/testenc1_enc"); 
     1581                        FileStream enc("testfiles" DIRECTORY_SEPARATOR  
     1582                                "testenc1_enc"); 
    15601583                        std::auto_ptr<BackupStoreFile::DecodedStream> decoded(BackupStoreFile::DecodeFileStream(enc, IOStream::TimeOutInfinite)); 
    15611584                        CollectInBufferStream d; 
     
    15711594                { 
    15721595                        #define FILE_SIZE_JUST_OVER     ((4096*2)+58) 
    1573                         FileStream f("testfiles/testenc2", O_WRONLY | O_CREAT | O_EXCL); 
     1596                        FileStream f("testfiles" DIRECTORY_SEPARATOR  
     1597                                "testenc2", O_WRONLY | O_CREAT | O_EXCL); 
    15741598                        f.Write(encfile + 2, FILE_SIZE_JUST_OVER); 
     1599                        f.Close(); 
    15751600                        BackupStoreFilenameClear name("testenc2"); 
    1576                         std::auto_ptr<IOStream> encoded(BackupStoreFile::EncodeFile("testfiles/testenc2", 32, name)); 
     1601                        std::auto_ptr<IOStream> encoded( 
     1602                                BackupStoreFile::EncodeFile( 
     1603                                        "testfiles" DIRECTORY_SEPARATOR 
     1604                                        "testenc2", 32, name)); 
    15771605                        CollectInBufferStream e; 
    15781606                        encoded->CopyStreamTo(e); 
     
    15901618                // Test that reordered streams work too 
    15911619                { 
    1592                         FileStream enc("testfiles/testenc1_enc"); 
     1620                        FileStream enc("testfiles" DIRECTORY_SEPARATOR  
     1621                                "testenc1_enc"); 
    15931622                        std::auto_ptr<IOStream> reordered(BackupStoreFile::ReorderFileToStreamOrder(&enc, false)); 
    15941623                        std::auto_ptr<BackupStoreFile::DecodedStream> decoded(BackupStoreFile::DecodeFileStream(*reordered, IOStream::TimeOutInfinite)); 
     
    16021631                } 
    16031632                 
     1633#ifndef WIN32            
    16041634                // Try out doing this on a symlink 
    16051635                { 
     
    16151645                        BackupStoreFile::DecodeFile(b, "testfiles/testsymlink_2", IOStream::TimeOutInfinite); 
    16161646                } 
     1647#endif 
    16171648        } 
    16181649 
     
    16201651        { 
    16211652                RaidFileWrite::CreateDirectory(0, "test-info"); 
    1622                 BackupStoreInfo::CreateNew(76, "test-info/", 0, 3461231233455433LL, 2934852487LL); 
    1623                 TEST_CHECK_THROWS(BackupStoreInfo::CreateNew(76, "test-info/", 0, 0, 0), RaidFileException, CannotOverwriteExistingFile); 
    1624                 std::auto_ptr<BackupStoreInfo> info(BackupStoreInfo::Load(76, "test-info/", 0, true)); 
     1653                BackupStoreInfo::CreateNew(76, "test-info" DIRECTORY_SEPARATOR,  
     1654                        0, 3461231233455433LL, 2934852487LL); 
     1655                TEST_CHECK_THROWS(BackupStoreInfo::CreateNew(76,  
     1656                        "test-info" DIRECTORY_SEPARATOR, 0, 0, 0),  
     1657                        RaidFileException, CannotOverwriteExistingFile); 
     1658                std::auto_ptr<BackupStoreInfo> info( 
     1659                        BackupStoreInfo::Load(76,  
     1660                                "test-info" DIRECTORY_SEPARATOR, 0, true)); 
    16251661                TEST_CHECK_THROWS(info->Save(), BackupStoreException, StoreInfoIsReadOnly); 
    16261662                TEST_CHECK_THROWS(info->ChangeBlocksUsed(1), BackupStoreException, StoreInfoIsReadOnly); 
     
    16311667        } 
    16321668        { 
    1633                 std::auto_ptr<BackupStoreInfo> info(BackupStoreInfo::Load(76, "test-info/", 0, false)); 
     1669                std::auto_ptr<BackupStoreInfo> info(BackupStoreInfo::Load(76,  
     1670                        "test-info" DIRECTORY_SEPARATOR, 0, false)); 
    16341671                info->ChangeBlocksUsed(8); 
    16351672                info->ChangeBlocksInOldFiles(9); 
     
    16491686        } 
    16501687        { 
    1651                 std::auto_ptr<BackupStoreInfo> info(BackupStoreInfo::Load(76, "test-info/", 0, true)); 
     1688                std::auto_ptr<BackupStoreInfo> info(BackupStoreInfo::Load(76,  
     1689                        "test-info" DIRECTORY_SEPARATOR, 0, true)); 
    16521690                TEST_THAT(info->GetBlocksUsed() == 7); 
    16531691                TEST_THAT(info->GetBlocksInOldFiles() == 5); 
     
    16671705        TLSContext context; 
    16681706        context.Initialise(false /* client */, 
    1669                         "testfiles/clientCerts.pem", 
    1670                         "testfiles/clientPrivKey.pem", 
    1671                         "testfiles/clientTrustedCAs.pem"); 
     1707                        "testfiles" DIRECTORY_SEPARATOR "clientCerts.pem", 
     1708                        "testfiles" DIRECTORY_SEPARATOR "clientPrivKey.pem", 
     1709                        "testfiles" DIRECTORY_SEPARATOR "clientTrustedCAs.pem"); 
    16721710 
    16731711        // First, try logging in without an account having been created... just make sure login fails. 
     1712 
     1713#ifdef WIN32 
     1714        int pid = LaunchServer("..\\..\\bin\\bbstored\\bbstored testfiles/bbstored.conf", "testfiles/bbstored.pid"); 
     1715#else 
    16741716        int pid = LaunchServer("../../bin/bbstored/bbstored testfiles/bbstored.conf", "testfiles/bbstored.pid"); 
     1717#endif 
     1718 
    16751719        TEST_THAT(pid != -1 && pid != 0); 
    16761720        if(pid > 0) 
     
    17011745 
    17021746                // Create an account for the test client 
     1747#ifdef WIN32 
     1748                TEST_THAT_ABORTONFAIL(::system("..\\..\\bin\\bbstoreaccounts\\bbstoreaccounts -c testfiles/bbstored.conf create 01234567 0 10000B 20000B") == 0); 
     1749#else 
    17031750                TEST_THAT_ABORTONFAIL(::system("../../bin/bbstoreaccounts/bbstoreaccounts -c testfiles/bbstored.conf create 01234567 0 10000B 20000B") == 0); 
    17041751                TestRemoteProcessMemLeaks("bbstoreaccounts.memleaks"); 
     1752#endif 
     1753 
    17051754                TEST_THAT(TestDirExists("testfiles/0_0/backup/01234567")); 
    17061755                TEST_THAT(TestDirExists("testfiles/0_1/backup/01234567")); 
     
    17261775                ::sleep(1); 
    17271776                TEST_THAT(!ServerIsAlive(pid)); 
     1777#ifndef WIN32 
    17281778                TestRemoteProcessMemLeaks("bbstored.memleaks"); 
     1779#endif 
    17291780                 
    17301781                // Set a new limit on the account -- leave the hard limit high to make sure the target for 
    17311782                // freeing space is the soft limit. 
     1783 
     1784#ifdef WIN32 
     1785                TEST_THAT_ABORTONFAIL(::system("..\\..\\bin\\bbstoreaccounts\\bbstoreaccounts -c testfiles/bbstored.conf setlimit 01234567 10B 20000B") == 0); 
     1786#else 
    17321787                TEST_THAT_ABORTONFAIL(::system("../../bin/bbstoreaccounts/bbstoreaccounts -c testfiles/bbstored.conf setlimit 01234567 10B 20000B") == 0); 
    17331788                TestRemoteProcessMemLeaks("bbstoreaccounts.memleaks"); 
     1789#endif 
    17341790 
    17351791                // Start things up 
     1792#ifdef WIN32 
     1793                pid = LaunchServer("..\\..\\bin\\bbstored\\bbstored testfiles/bbstored.conf", "testfiles/bbstored.pid"); 
     1794#else 
    17361795                pid = LaunchServer("../../bin/bbstored/bbstored testfiles/bbstored.conf", "testfiles/bbstored.pid"); 
     1796#endif 
     1797 
    17371798                ::sleep(1); 
    17381799                TEST_THAT(ServerIsAlive(pid)); 
     
    17591820                 
    17601821                // Set a really small hard limit 
     1822#ifdef WIN32 
     1823                TEST_THAT_ABORTONFAIL(::system("..\\..\\bin\\bbstoreaccounts\\bbstoreaccounts -c testfiles/bbstored.conf setlimit 01234567 10B 20B") == 0); 
     1824#else 
    17611825                TEST_THAT_ABORTONFAIL(::system("../../bin/bbstoreaccounts/bbstoreaccounts -c testfiles/bbstored.conf setlimit 01234567 10B 20B") == 0); 
    17621826                TestRemoteProcessMemLeaks("bbstoreaccounts.memleaks"); 
     1827#endif 
    17631828 
    17641829                // Try to upload a file and create a directory, and check an error is generated 
     
    18091874                ::sleep(1); 
    18101875                TEST_THAT(!ServerIsAlive(pid)); 
     1876 
     1877#ifndef WIN32 
    18111878                TestRemoteProcessMemLeaks("bbstored.memleaks"); 
     1879#endif 
    18121880        } 
    18131881 
     
    18211889        // Create an account for the test client 
    18221890        TEST_THAT_ABORTONFAIL(::system("../../bin/bbstoreaccounts/bbstoreaccounts -c testfiles/bbstored.conf create 01234567 0 30000B 40000B") == 0); 
     1891 
     1892#ifndef WIN32 
    18231893        TestRemoteProcessMemLeaks("bbstoreaccounts.memleaks"); 
     1894#endif 
    18241895 
    18251896        // First, try logging in without an account having been created... just make sure login fails. 
     1897 
     1898#ifdef WIN32 
     1899        int pid = LaunchServer("..\\..\\bin\\bbstored\\bbstored testfiles/bbstored_multi.conf", "testfiles/bbstored.pid"); 
     1900#else 
    18261901        int pid = LaunchServer("../../bin/bbstored/bbstored testfiles/bbstored_multi.conf", "testfiles/bbstored.pid"); 
     1902#endif 
     1903 
    18271904        TEST_THAT(pid != -1 && pid != 0); 
    18281905        if(pid > 0) 
     
    18411918                ::sleep(1); 
    18421919                TEST_THAT(!ServerIsAlive(pid)); 
     1920#ifndef WIN32 
    18431921                TestRemoteProcessMemLeaks("bbstored.memleaks"); 
     1922#endif 
    18441923        } 
    18451924 
     
    18481927} 
    18491928 
     1929#ifdef WIN32 
     1930WCHAR* ConvertUtf8ToWideString(const char* pString); 
     1931std::string ConvertPathToAbsoluteUnicode(const char *pFileName); 
     1932#endif 
     1933 
    18501934int test(int argc, const char *argv[]) 
    18511935{ 
     1936#ifdef WIN32 
     1937        // Under win32 we must initialise the Winsock library 
     1938        // before using sockets 
     1939 
     1940        WSADATA info; 
     1941        TEST_THAT(WSAStartup(0x0101, &info) != SOCKET_ERROR) 
     1942 
     1943        // this had better work, or bbstored will die when combining diffs 
     1944        char* file = "foo"; 
     1945        std::string abs = ConvertPathToAbsoluteUnicode(file); 
     1946        WCHAR* wfile = ConvertUtf8ToWideString(abs.c_str()); 
     1947 
     1948        DWORD accessRights = FILE_READ_ATTRIBUTES |  
     1949                FILE_LIST_DIRECTORY | FILE_READ_EA | FILE_WRITE_ATTRIBUTES | 
     1950                FILE_WRITE_DATA | FILE_WRITE_EA /*| FILE_ALL_ACCESS*/; 
     1951        DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; 
     1952 
     1953        HANDLE h1 = CreateFileW(wfile, accessRights, shareMode, 
     1954                NULL, OPEN_ALWAYS, FILE_FLAG_BACKUP_SEMANTICS, NULL); 
     1955        assert(h1 != INVALID_HANDLE_VALUE); 
     1956        TEST_THAT(h1 != INVALID_HANDLE_VALUE); 
     1957 
     1958        accessRights = FILE_READ_ATTRIBUTES |  
     1959                FILE_LIST_DIRECTORY | FILE_READ_EA; 
     1960 
     1961        HANDLE h2 = CreateFileW(wfile, accessRights, shareMode, 
     1962                NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); 
     1963        assert(h2 != INVALID_HANDLE_VALUE); 
     1964        TEST_THAT(h2 != INVALID_HANDLE_VALUE); 
     1965 
     1966        CloseHandle(h2); 
     1967        CloseHandle(h1); 
     1968 
     1969        h1 = openfile("foo", O_CREAT | O_RDWR, 0); 
     1970        TEST_THAT(h1 != INVALID_HANDLE_VALUE); 
     1971        h2 = openfile("foo", O_RDWR, 0); 
     1972        TEST_THAT(h2 != INVALID_HANDLE_VALUE); 
     1973        CloseHandle(h2); 
     1974        CloseHandle(h1); 
     1975#endif 
     1976 
    18521977        // SSL library 
    18531978        SSLLib::Initialise(); 
     
    18661991        // Use the setup crypto command to set up all these keys, so that the bbackupquery command can be used 
    18671992        // for seeing what's going on. 
     1993#ifdef WIN32 
     1994        BackupClientCryptoKeys_Setup("testfiles\\bbackupd.keys");        
     1995#else 
    18681996        BackupClientCryptoKeys_Setup("testfiles/bbackupd.keys");         
     1997#endif 
    18691998         
    18701999        // encode in some filenames -- can't do static initialisation because the key won't be set up when these are initialised 
  • box/chris/merge/test/backupstorefix/testfiles/testbackupstorefix.pl.in

    r537 r710  
    5555        while(<INITIAL>) 
    5656        { 
    57                 chomp; 
     57                chomp; s/\r//; 
    5858                $expected{$_} = 1; 
    5959                m/\A(.+?) .+? (.+)\Z/; 
     
    100100        { 
    101101                print LISTING_COPY; 
    102                 chomp; 
     102                chomp; s/\r//; 
    103103                s/\[FILENAME NOT ENCRYPTED\]//; 
    104104                if(exists $expected{$_}) 
  • box/chris/merge/test/backupstorepatch/testbackupstorepatch.cpp

    r341 r710  
    284284int test(int argc, const char *argv[]) 
    285285{ 
     286#ifdef WIN32 
     287        // Under win32 we must initialise the Winsock library 
     288        // before using sockets 
     289 
     290        WSADATA info; 
     291        TEST_THAT(WSAStartup(0x0101, &info) != SOCKET_ERROR) 
     292#endif 
     293 
    286294        // Allocate a buffer 
    287295        buffer = ::malloc(BUFFER_SIZE); 
     
    310318 
    311319        // Create an account 
     320#ifdef WIN32 
     321        TEST_THAT_ABORTONFAIL(::system("..\\..\\bin\\bbstoreaccounts\\bbstoreaccounts -c testfiles/bbstored.conf create 01234567 0 30000B 40000B") == 0); 
     322#else 
    312323        TEST_THAT_ABORTONFAIL(::system("../../bin/bbstoreaccounts/bbstoreaccounts -c testfiles/bbstored.conf create 01234567 0 30000B 40000B") == 0); 
    313324        TestRemoteProcessMemLeaks("bbstoreaccounts.memleaks"); 
     325#endif 
    314326 
    315327        // Create test files 
     
    320332 
    321333        // First, try logging in without an account having been created... just make sure login fails. 
     334#ifdef WIN32 
     335        int pid = LaunchServer("..\\..\\bin\\bbstored\\bbstored testfiles/bbstored.conf", "testfiles/bbstored.pid"); 
     336#else 
    322337        int pid = LaunchServer("../../bin/bbstored/bbstored testfiles/bbstored.conf", "testfiles/bbstored.pid"); 
     338#endif 
     339 
    323340        TEST_THAT(pid != -1 && pid != 0); 
    324341        if(pid > 0) 
     
    398415                                        test_files[f].IDOnServer = stored->GetObjectID(); 
    399416                                        test_files[f].IsCompletelyDifferent = isCompletelyDifferent; 
    400                                         printf("ID %lld, completely different: %s\n", test_files[f].IDOnServer, 
     417 
     418#ifdef WIN32 
     419                                        printf("ID %I64d, completely different: %s\n", 
     420#else 
     421                                        printf("ID %lld, completely different: %s\n",  
     422#endif 
     423                                                test_files[f].IDOnServer, 
    401424                                                test_files[f].IsCompletelyDifferent?"yes":"no");                         
    402425                                } 
     
    566589                        } 
    567590 
    568                         // Send the server a restart signal, so it does housekeeping immedaitely, and wait for it to happen 
     591#ifdef WIN32 
     592                        wait_for_operation(12); 
     593#else 
     594                        // Send the server a restart signal, so it does housekeeping immediately, and wait for it to happen 
    569595                        ::sleep(1);     // wait for old connections to terminate 
    570596                        ::kill(pid, SIGHUP); 
     597#endif 
     598 
    571599                        // Get the revision number of the info file 
    572600                        int64_t first_revision = 0; 
     
    612640                TEST_THAT(KillServer(pid)); 
    613641                TEST_THAT(!ServerIsAlive(pid)); 
     642 
     643                #ifndef WIN32 
    614644                TestRemoteProcessMemLeaks("bbstored.memleaks"); 
     645                #endif 
    615646        } 
    616647         
  • box/chris/merge/test/basicserver/TestCommands.cpp

    r217 r710  
    22#include "Box.h" 
    33 
     4#ifdef HAVE_SYSLOG_H 
    45#include <syslog.h> 
     6#endif 
    57 
    68#include "autogen_TestProtocolServer.h" 
  • box/chris/merge/test/basicserver/testbasicserver.cpp

    r217 r710  
    3232#include "MemLeakFindOn.h" 
    3333 
    34  
    3534#define SERVER_LISTEN_PORT      2003 
    3635 
     
    6362void testservers_pause_before_reply() 
    6463{ 
    65          struct timespec t; 
    66          t.tv_sec = 0; 
    67          t.tv_nsec = COMMS_SERVER_WAIT_BEFORE_REPLYING * 1000 * 1000;   // convert to ns 
    68          ::nanosleep(&t, NULL); 
     64#ifdef WIN32 
     65        Sleep(COMMS_SERVER_WAIT_BEFORE_REPLYING); 
     66#else 
     67        struct timespec t; 
     68        t.tv_sec = 0; 
     69        t.tv_nsec = COMMS_SERVER_WAIT_BEFORE_REPLYING * 1000 * 1000;    // convert to ns 
     70        ::nanosleep(&t, NULL); 
     71#endif 
    6972} 
    7073 
     
    428431        } 
    429432 
     433#ifdef WIN32 
     434        // Under win32 we must initialise the Winsock library 
     435        // before using sockets 
     436 
     437        WSADATA info; 
     438        TEST_THAT(WSAStartup(0x0101, &info) != SOCKET_ERROR) 
     439#endif 
     440 
    430441//printf("SKIPPING TESTS------------------------\n"); 
    431442//goto protocolserver; 
     
    433444        // Launch a basic server 
    434445        { 
    435                 int pid = LaunchServer("./test srv1 testfiles/srv1.conf", "testfiles/srv1.pid"); 
     446#ifdef WIN32 
     447                int pid = LaunchServer("test srv1 testfiles\\srv1.conf",  
     448                        "testfiles\\srv1.pid"); 
     449#else 
     450                int pid = LaunchServer("./test srv1 testfiles/srv1.conf",  
     451                        "testfiles/srv1.pid"); 
     452#endif 
     453 
    436454                TEST_THAT(pid != -1 && pid != 0); 
    437455                if(pid > 0) 
    438456                { 
    439457                        // Check that it's written the expected file 
    440                         TEST_THAT(TestFileExists("testfiles/srv1.test1")); 
     458                        TEST_THAT(TestFileExists("testfiles"  
     459                                DIRECTORY_SEPARATOR "srv1.test1")); 
    441460                        TEST_THAT(ServerIsAlive(pid)); 
    442461                        // Move the config file over 
    443                         TEST_THAT(::rename("testfiles/srv1b.conf", "testfiles/srv1.conf") != -1); 
     462#ifdef WIN32 
     463                        TEST_THAT(::unlink("testfiles" DIRECTORY_SEPARATOR  
     464                                "srv1.conf") != -1); 
     465#endif 
     466                        TEST_THAT(::rename( 
     467                                "testfiles" DIRECTORY_SEPARATOR "srv1b.conf",  
     468                                "testfiles" DIRECTORY_SEPARATOR "srv1.conf")  
     469                                != -1); 
     470#ifndef WIN32 
    444471                        // Get it to reread the config file 
    445472                        TEST_THAT(HUPServer(pid)); 
     
    447474                        TEST_THAT(ServerIsAlive(pid)); 
    448475                        // Check that new file exists 
    449                         TEST_THAT(TestFileExists("testfiles/srv1.test2")); 
     476                        TEST_THAT(TestFileExists("testfiles"  
     477                                DIRECTORY_SEPARATOR "srv1.test2")); 
     478#endif // !WIN32 
    450479                        // Kill it off 
    451480                        TEST_THAT(KillServer(pid)); 
     481#ifndef WIN32 
    452482                        TestRemoteProcessMemLeaks("generic-daemon.memleaks"); 
     483#endif // !WIN32 
    453484                } 
    454485        } 
     
    456487        // Launch a test forking server 
    457488        { 
    458                 int pid = LaunchServer("./test srv2 testfiles/srv2.conf", "testfiles/srv2.pid"); 
     489#ifdef WIN32 
     490                int pid = LaunchServer("test srv2 testfiles\\srv2.conf",  
     491                        "testfiles\\srv2.pid"); 
     492#else 
     493                int pid = LaunchServer("./test srv2 testfiles/srv2.conf",  
     494                        "testfiles/srv2.pid"); 
     495#endif 
     496 
    459497                TEST_THAT(pid != -1 && pid != 0); 
    460498                if(pid > 0) 
     
    462500                        // Will it restart? 
    463501                        TEST_THAT(ServerIsAlive(pid)); 
     502#ifndef WIN32 
    464503                        TEST_THAT(HUPServer(pid)); 
    465504                        ::sleep(1); 
    466505                        TEST_THAT(ServerIsAlive(pid)); 
     506#endif // !WIN32 
    467507                        // Make some connections 
    468508                        { 
    469509                                SocketStream conn1; 
    470510                                conn1.Open(Socket::TypeINET, "localhost", 2003); 
     511#ifndef WIN32 
    471512                                SocketStream conn2; 
    472513                                conn2.Open(Socket::TypeUNIX, "testfiles/srv2.sock"); 
    473514                                SocketStream conn3; 
    474515                                conn3.Open(Socket::TypeINET, "localhost", 2003); 
     516#endif // !WIN32 
    475517                                // Quick check that reconnections fail 
    476518                                TEST_CHECK_THROWS(conn1.Open(Socket::TypeUNIX, "testfiles/srv2.sock");, ServerException, SocketAlreadyOpen); 
     
    478520                                std::vector<IOStream *> conns; 
    479521                                conns.push_back(&conn1); 
     522#ifndef WIN32 
    480523                                conns.push_back(&conn2); 
    481524                                conns.push_back(&conn3); 
     525#endif // !WIN32 
    482526                                Srv2TestConversations(conns); 
    483527                                // Implicit close 
    484528                        } 
     529#ifndef WIN32 
    485530                        // HUP again 
    486531                        TEST_THAT(HUPServer(pid)); 
    487532                        ::sleep(1); 
    488533                        TEST_THAT(ServerIsAlive(pid)); 
     534#endif // !WIN32 
    489535                        // Kill it 
    490536                        TEST_THAT(KillServer(pid)); 
    491537                        ::sleep(1); 
    492538                        TEST_THAT(!ServerIsAlive(pid)); 
     539#ifndef WIN32 
    493540                        TestRemoteProcessMemLeaks("test-srv2.memleaks"); 
     541#endif // !WIN32 
    494542                } 
    495543        } 
     
    497545        // Launch a test SSL server 
    498546        { 
     547#ifdef WIN32 
     548                int pid = LaunchServer("test srv3 testfiles\\srv3.conf",  
     549                        "testfiles\\srv3.pid"); 
     550#else 
    499551                int pid = LaunchServer("./test srv3 testfiles/srv3.conf", "testfiles/srv3.pid"); 
     552#endif 
    500553                TEST_THAT(pid != -1 && pid != 0); 
    501554                if(pid > 0) 
     
    503556                        // Will it restart? 
    504557                        TEST_THAT(ServerIsAlive(pid)); 
     558 
     559#ifndef WIN32 
    505560                        TEST_THAT(HUPServer(pid)); 
    506561                        ::sleep(1); 
    507562                        TEST_THAT(ServerIsAlive(pid)); 
     563#endif 
     564 
    508565                        // Make some connections 
    509566                        { 
     
    520577                                SocketStreamTLS conn1; 
    521578                                conn1.Open(context, Socket::TypeINET, "localhost", 2003); 
     579#ifndef WIN32 
    522580                                SocketStreamTLS conn2; 
    523581                                conn2.Open(context, Socket::TypeUNIX, "testfiles/srv3.sock"); 
    524582                                SocketStreamTLS conn3; 
    525583                                conn3.Open(context, Socket::TypeINET, "localhost", 2003); 
     584#endif 
    526585                                // Quick check that reconnections fail 
    527586                                TEST_CHECK_THROWS(conn1.Open(context, Socket::TypeUNIX, "testfiles/srv3.sock");, ServerException, SocketAlreadyOpen); 
     
    529588                                std::vector<IOStream *> conns; 
    530589                                conns.push_back(&conn1); 
     590#ifndef WIN32 
    531591                                conns.push_back(&conn2); 
    532592                                conns.push_back(&conn3); 
     593#endif 
    533594                                Srv2TestConversations(conns); 
    534595                                // Implicit close 
    535596                        } 
     597#ifndef WIN32 
    536598                        // HUP again 
    537599                        TEST_THAT(HUPServer(pid)); 
    538600                        ::sleep(1); 
    539601                        TEST_THAT(ServerIsAlive(pid)); 
     602#endif 
    540603                        // Kill it 
    541604                        TEST_THAT(KillServer(pid)); 
    542605                        ::sleep(1); 
    543606                        TEST_THAT(!ServerIsAlive(pid)); 
     607#ifndef WIN32 
    544608                        TestRemoteProcessMemLeaks("test-srv3.memleaks"); 
     609#endif 
    545610                } 
    546611        } 
     
    549614        // Launch a test protocol handling server 
    550615        { 
    551                 int pid = LaunchServer("./test srv4 testfiles/srv4.conf", "testfiles/srv4.pid"); 
     616#ifdef WIN32 
     617                int pid = LaunchServer("test srv4 testfiles\\srv4.conf",  
     618                        "testfiles\\srv4.pid"); 
     619#else 
     620                int pid = LaunchServer("./test srv4 testfiles/srv4.conf",  
     621                        "testfiles/srv4.pid"); 
     622#endif 
    552623                TEST_THAT(pid != -1 && pid != 0); 
    553624                if(pid > 0) 
     
    558629                        // Open a connection to it               
    559630                        SocketStream conn; 
     631#ifdef WIN32 
     632                        conn.Open(Socket::TypeINET, "localhost", 2003); 
     633#else 
    560634                        conn.Open(Socket::TypeUNIX, "testfiles/srv4.sock"); 
     635#endif 
    561636                         
    562637                        // Create a protocol 
     
    621696                        ::sleep(1); 
    622697                        TEST_THAT(!ServerIsAlive(pid)); 
     698#ifndef WIN32 
    623699                        TestRemoteProcessMemLeaks("test-srv4.memleaks"); 
     700#endif 
    624701                } 
    625702        } 
  • box/chris/merge/test/bbackupd/testbbackupd.cpp

    r462 r710  
    719719                        wait_for_backup_operation(); 
    720720                        compareReturnValue = ::system("../../bin/bbackupquery/bbackupquery -q -c testfiles/bbackupd.conf -l testfiles/query3e.log \"compare -ac\" quit"); 
    721                         TEST_THAT(compareReturnValue == 2*256); // should find differences 
     721                        TEST_THAT(compareReturnValue == 3*256); // should find differences 
    722722                        TestRemoteProcessMemLeaks("bbackupquery.memleaks"); 
    723723                        // Check that it was reported correctly 
  • box/chris/merge/test/bbackupd/testfiles/extcheck1.pl.in

    r537 r710  
    22use strict; 
    33 
    4 unless(open IN,"../../bin/bbackupquery/bbackupquery -q -c testfiles/bbackupd.conf -l testfiles/query4.log \"compare -ac\" quit|") 
     4my $flags = $ARGV[0] or ""; 
     5 
     6unless(open IN,"../../bin/bbackupquery/bbackupquery -q -c testfiles/bbackupd.conf -l testfiles/query4.log \"compare -ac$flags\" quit|") 
    57{ 
    68        print "Couldn't open compare utility\n"; 
     
    1618        if(m/continousupdate/) 
    1719        { 
    18                 $ret = 2 unless m/exists/; 
     20                unless (/exists/) 
     21                { 
     22                        print "FAIL: continousupdate line does not match\n"; 
     23                        $ret = 2; 
     24                } 
    1925                $seen = 1; 
    2026        } 
    2127        else 
    2228        { 
    23                 $ret = 2 unless m/\AWARNING/ || m/\ADifferences/ || /might be reason/ || /probably due to file mod/; 
     29                unless (/\AWARNING/ or /\ADifferences/ or /might be reason/ 
     30                        or /probably due to file mod/) 
     31                { 
     32                        print "FAIL: Summary line does not match\n"; 
     33                        $ret = 2; 
     34                } 
    2435        } 
    25         print; 
     36        print "READ: $_"; 
    2637} 
    2738 
  • box/chris/merge/test/bbackupd/testfiles/extcheck2.pl.in

    r537 r710  
    22use strict; 
    33 
    4 unless(open IN,"../../bin/bbackupquery/bbackupquery -q -c testfiles/bbackupd.conf -l testfiles/query4.log \"compare -ac\" quit|") 
     4my $flags = $ARGV[0] or ""; 
     5 
     6unless(open IN,"../../bin/bbackupquery/bbackupquery -q -c testfiles/bbackupd.conf -l testfiles/query4.log \"compare -ac$flags\" quit|") 
    57{ 
    68        print "Couldn't open compare utility\n"; 
     
    1517        if(m/continousupdate/) 
    1618        { 
    17                 $ret = 2 unless m/contents/ || m/attributes/; 
     19                unless (m/contents/ or m/attributes/) 
     20                { 
     21                        print "FAIL: continuousupdate line does not match\n"; 
     22                        $ret = 2; 
     23                } 
    1824        } 
    1925        else 
    2026        { 
    21                 $ret = 2 unless m/\AWARNING/ || m/\ADifferences/ || /might be reason/ || /probably due to file mod/; 
     27                unless (/\AWARNING/ or /\ADifferences/ or /might be reason/  
     28                        or /probably due to file mod/) 
     29                { 
     30                        print "FAIL: summary line does not match\n"; 
     31                        $ret = 2; 
     32                } 
    2233        } 
    23         print; 
     34 
     35        print "READ: $_"; 
    2436} 
    2537 
  • box/chris/merge/test/common/testcommon.cpp

    r219 r710  
    2525#include "Conversion.h" 
    2626#include "autogen_ConversionException.h" 
     27#include "CollectInBufferStream.h" 
     28#include "Archive.h" 
    2729 
    2830#include "MemLeakFindOn.h" 
     
    566568        test_conversions(); 
    567569 
     570        // test that we can use Archive and CollectInBufferStream 
     571        // to read and write arbitrary types to a memory buffer 
     572 
     573        { 
     574                CollectInBufferStream buffer; 
     575                ASSERT(buffer.GetPosition() == 0); 
     576 
     577                { 
     578                        Archive archive(buffer, 0); 
     579                        ASSERT(buffer.GetPosition() == 0); 
     580 
     581                        archive.Write((bool) true); 
     582                        archive.Write((bool) false); 
     583                        archive.Write((int) 0x12345678); 
     584                        archive.Write((int) 0x87654321); 
     585                        archive.Write((int64_t)  0x0badfeedcafebabeLL); 
     586                        archive.Write((uint64_t) 0xfeedfacedeadf00dLL); 
     587                        archive.Write((uint8_t)  0x01); 
     588                        archive.Write((uint8_t)  0xfe); 
     589                        archive.Write(std::string("hello world!")); 
     590                        archive.Write(std::string("goodbye cruel world!")); 
     591                } 
     592 
     593                CollectInBufferStream buf2; 
     594                buf2.Write(buffer.GetBuffer(), buffer.GetSize()); 
     595                TEST_THAT(buf2.GetPosition() == buffer.GetSize()); 
     596 
     597                buf2.SetForReading(); 
     598                TEST_THAT(buf2.GetPosition() == 0); 
     599 
     600                { 
     601                        Archive archive(buf2, 0); 
     602                        TEST_THAT(buf2.GetPosition() == 0); 
     603 
     604                        bool b; 
     605                        archive.Read(b); TEST_THAT(b == true); 
     606                        archive.Read(b); TEST_THAT(b == false); 
     607 
     608                        int i; 
     609                        archive.Read(i); TEST_THAT(i == 0x12345678); 
     610                        archive.Read(i); TEST_THAT((unsigned int)i == 0x87654321); 
     611 
     612                        uint64_t i64; 
     613                        archive.Read(i64); TEST_THAT(i64 == 0x0badfeedcafebabeLL); 
     614                        archive.Read(i64); TEST_THAT(i64 == 0xfeedfacedeadf00dLL); 
     615 
     616                        uint8_t i8; 
     617                        archive.Read(i8); TEST_THAT(i8 == 0x01); 
     618                        archive.Read(i8); TEST_THAT(i8 == 0xfe); 
     619 
     620                        std::string s; 
     621                        archive.Read(s); TEST_THAT(s == "hello world!"); 
     622                        archive.Read(s); TEST_THAT(s == "goodbye cruel world!"); 
     623 
     624                        TEST_THAT(!buf2.StreamDataLeft()); 
     625                } 
     626        } 
     627 
    568628        return 0; 
    569629} 
  • box/chris/merge/test/raidfile/intercept.cpp

    r310 r710  
    1515#include <sys/types.h> 
    1616#include <unistd.h> 
     17 
     18#ifdef HAVE_SYS_UIO_H 
    1719#include <sys/uio.h> 
     20#endif 
     21 
    1822#include <errno.h> 
    1923 
  • box/chris/merge/test/raidfile/testraidfile.cpp

    r217 r710  
    1313#include <unistd.h> 
    1414#include <errno.h> 
     15 
     16#ifdef HAVE_SYSCALL 
    1517#include <sys/syscall.h> 
     18#endif 
    1619 
    1720#include <string.h> 
     
    208211        } 
    209212        TEST_THAT(!readstream4.StreamDataLeft());               // check IOStream interface is correct 
     213        pread.reset(); 
    210214 
    211215        // Be nasty, and create some errors for the RAID stuff to recover from... 
     
    213217        { 
    214218                char stripe1fn[256], stripe1fnRename[256]; 
    215                 sprintf(stripe1fn, "testfiles/%d_%d/%s.rf", set, startDisc, filename); 
    216                 sprintf(stripe1fnRename, "testfiles/%d_%d/%s.rf-REMOVED", set, startDisc, filename); 
     219                sprintf(stripe1fn, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     220                        DIRECTORY_SEPARATOR "%s.rf", set, startDisc, filename); 
     221                sprintf(stripe1fnRename, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     222                        DIRECTORY_SEPARATOR "%s.rf-REMOVED", set, startDisc,  
     223                        filename); 
    217224                char stripe2fn[256], stripe2fnRename[256]; 
    218                 sprintf(stripe2fn, "testfiles/%d_%d/%s.rf", set, (startDisc + 1) % RAID_NUMBER_DISCS, filename); 
    219                 sprintf(stripe2fnRename, "testfiles/%d_%d/%s.rf-REMOVED", set, (startDisc + 1) % RAID_NUMBER_DISCS, filename); 
     225                sprintf(stripe2fn, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     226                        DIRECTORY_SEPARATOR "%s.rf", set,  
     227                        (startDisc + 1) % RAID_NUMBER_DISCS, filename); 
     228                sprintf(stripe2fnRename, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     229                        DIRECTORY_SEPARATOR "%s.rf-REMOVED", set,  
     230                        (startDisc + 1) % RAID_NUMBER_DISCS, filename); 
    220231 
    221232                // Read with stripe1 + parity            
     
    253264                mungefilename[m++] = '\0'; 
    254265                char stripe1munge[256]; 
    255                 sprintf(stripe1munge, "testfiles/%d_%d/.raidfile-unreadable/%s", set, startDisc, mungefilename); 
     266                sprintf(stripe1munge, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     267                        DIRECTORY_SEPARATOR ".raidfile-unreadable" 
     268                        DIRECTORY_SEPARATOR "%s", set, startDisc,  
     269                        mungefilename); 
    256270                char stripe2munge[256]; 
    257                 sprintf(stripe2munge, "testfiles/%d_%d/.raidfile-unreadable/%s", set, (startDisc + 1) % RAID_NUMBER_DISCS, mungefilename); 
     271                sprintf(stripe2munge, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     272                        DIRECTORY_SEPARATOR ".raidfile-unreadable" 
     273                        DIRECTORY_SEPARATOR "%s", set,  
     274                        (startDisc + 1) % RAID_NUMBER_DISCS, mungefilename); 
    258275                 
    259276 
     
    360377        // This time, don't discard and transform it to a RAID File 
    361378        char writefnPre[256]; 
    362         sprintf(writefnPre, "testfiles/%d_%d/%s.rfwX", set, startDisc, filename); 
     379        sprintf(writefnPre, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     380                DIRECTORY_SEPARATOR "%s.rfwX", set, startDisc, filename); 
    363381        TEST_THAT(TestFileExists(writefnPre)); 
    364382        char writefn[256]; 
    365         sprintf(writefn, "testfiles/%d_%d/%s.rfw", set, startDisc, filename); 
     383        sprintf(writefn, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     384                DIRECTORY_SEPARATOR "%s.rfw", set, startDisc, filename); 
    366385        int usageInBlocks = write4.GetDiscUsageInBlocks(); 
    367386        write4.Commit(DoTransform); 
     
    391410                } 
    392411                char stripe1fn[256]; 
    393                 sprintf(stripe1fn, "testfiles/%d_%d/%s.rf", set, startDisc, filename); 
     412                sprintf(stripe1fn, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     413                        DIRECTORY_SEPARATOR "%s.rf", set, startDisc, filename); 
    394414                TEST_THAT(TestGetFileSize(stripe1fn) == fs1); 
    395415                char stripe2fn[256]; 
    396                 sprintf(stripe2fn, "testfiles/%d_%d/%s.rf", set, (startDisc + 1) % RAID_NUMBER_DISCS, filename); 
     416                sprintf(stripe2fn, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     417                        DIRECTORY_SEPARATOR "%s.rf", set,  
     418                        (startDisc + 1) % RAID_NUMBER_DISCS, filename); 
    397419                TEST_THAT(TestGetFileSize(stripe2fn) == (int)(datasize - fs1)); 
    398420                // Parity file size 
    399421                char parityfn[256]; 
    400                 sprintf(parityfn, "testfiles/%d_%d/%s.rf", set, (startDisc + 2) % RAID_NUMBER_DISCS, filename); 
     422                sprintf(parityfn, "testfiles" DIRECTORY_SEPARATOR "%d_%d" 
     423                        DIRECTORY_SEPARATOR "%s.rf", set,  
     424                        (startDisc + 2) % RAID_NUMBER_DISCS, filename); 
    401425                // Mildly complex calculation 
    402426                unsigned int blocks = datasize / RAID_BLOCK_SIZE; 
     
    437461                { 
    438462                        int f; 
    439                         TEST_THAT((f = ::open(stripe1fn, O_RDONLY, 0)) != -1); 
     463                        TEST_THAT((f = ::open(stripe1fn, O_RDONLY | O_BINARY,  
     464                                0)) != -1); 
    440465                        TEST_THAT(sizeof(testblock) == ::read(f, testblock, sizeof(testblock))); 
    441466                        for(unsigned int q = 0; q < sizeof(testblock); ++q) 
     
    444469                        } 
    445470                        ::close(f); 
    446                         TEST_THAT((f = ::open(stripe2fn, O_RDONLY, 0)) != -1); 
     471                        TEST_THAT((f = ::open(stripe2fn, O_RDONLY | O_BINARY,  
     472                                0)) != -1); 
    447473                        TEST_THAT(sizeof(testblock) == ::read(f, testblock, sizeof(testblock))); 
    448474                        for(unsigned int q = 0; q < sizeof(testblock); ++q) 
     
    537563        // Generate a random pre-existing write file (and ensure that it doesn't exist already) 
    538564        int f; 
    539         TEST_THAT((f = ::open("testfiles/0_2/overwrite_B.rfwX", O_WRONLY | O_CREAT | O_EXCL, 0755)) != -1); 
     565        TEST_THAT((f = ::open("testfiles" DIRECTORY_SEPARATOR "0_2"  
     566                DIRECTORY_SEPARATOR "overwrite_B.rfwX",  
     567                O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0755)) != -1); 
    540568        TEST_THAT(::write(f, "TESTTEST", 8) == 8); 
    541569        ::close(f); 
     
    558586        // Initialise the controller 
    559587        RaidFileController &rcontroller = RaidFileController::GetController(); 
    560         rcontroller.Initialise("testfiles/raidfile.conf"); 
     588        rcontroller.Initialise("testfiles" DIRECTORY_SEPARATOR "raidfile.conf"); 
    561589 
    562590        // some data 
     
    575603        // Try creating a directory 
    576604        RaidFileWrite::CreateDirectory(0, "test-dir"); 
    577         TEST_THAT(TestDirExists("testfiles/0_0/test-dir")); 
    578         TEST_THAT(TestDirExists("testfiles/0_1/test-dir")); 
    579         TEST_THAT(TestDirExists("testfiles/0_2/test-dir")); 
     605        TEST_THAT(TestDirExists("testfiles" DIRECTORY_SEPARATOR "0_0"  
     606                DIRECTORY_SEPARATOR "test-dir")); 
     607        TEST_THAT(TestDirExists("testfiles" DIRECTORY_SEPARATOR "0_1" 
     608                DIRECTORY_SEPARATOR "test-dir")); 
     609        TEST_THAT(TestDirExists("testfiles" DIRECTORY_SEPARATOR "0_2" 
     610                DIRECTORY_SEPARATOR "test-dir")); 
    580611        TEST_THAT(RaidFileRead::DirectoryExists(0, "test-dir")); 
    581612        TEST_THAT(!RaidFileRead::DirectoryExists(0, "test-dir-not")); 
     
    609640        // Before it's deleted, check to see the contents are as expected 
    610641        int f; 
    611         TEST_THAT((f = ::open("testfiles/0_2/test1.rfwX", O_RDONLY, 0)) >= 0); 
     642        TEST_THAT((f = ::open("testfiles" DIRECTORY_SEPARATOR "0_2" 
     643                DIRECTORY_SEPARATOR "test1.rfwX", O_RDONLY | O_BINARY, 0))  
     644                >= 0); 
    612645        char buffer[sizeof(data)]; 
    613         TEST_THAT(::read(f, buffer, sizeof(buffer)) == sizeof(buffer)); 
     646        int bytes_read = ::read(f, buffer, sizeof(buffer)); 
     647        TEST_THAT(bytes_read == sizeof(buffer)); 
    614648        for(unsigned int l = 0; l < 1024; ++l) 
    615649        { 
     
    625659        } 
    626660        TEST_THAT(::lseek(f, sizeof(data), SEEK_SET) == sizeof(buffer)); 
    627         TEST_THAT(::read(f, buffer, sizeof(buffer)) == sizeof(buffer)); 
     661        bytes_read = ::read(f, buffer, sizeof(buffer)); 
     662        TEST_THAT(bytes_read == sizeof(buffer)); 
    628663        for(unsigned int l = 0; l < 1024; ++l) 
    629664        { 
     
    636671        // Commit the data 
    637672        write1.Commit(); 
    638         TEST_THAT((f = ::open("testfiles/0_2/test1.rfw", O_RDONLY, 0)) >= 0); 
     673        TEST_THAT((f = ::open("testfiles" DIRECTORY_SEPARATOR "0_2" 
     674                DIRECTORY_SEPARATOR "test1.rfw", O_RDONLY | O_BINARY, 0))  
     675                >= 0); 
    639676        ::close(f); 
    640677 
     
    688725        // This time, discard it 
    689726        write2.Discard(); 
    690         TEST_THAT((f = ::open("testfiles/0_2/test1.rfw", O_RDONLY, 0)) == -1); 
     727        TEST_THAT((f = ::open("testfiles" DIRECTORY_SEPARATOR "0_2" 
     728                DIRECTORY_SEPARATOR "test1.rfw", O_RDONLY | O_BINARY, 0))  
     729                == -1); 
    691730         
    692731        // And leaving it there... 
     
    696735        // This time, commit it 
    697736        writeLeave.Commit(); 
    698         TEST_THAT((f = ::open("testfiles/0_2/test1.rfw", O_RDONLY, 0)) != -1); 
     737        TEST_THAT((f = ::open("testfiles" DIRECTORY_SEPARATOR "0_2"  
     738                DIRECTORY_SEPARATOR "test1.rfw", O_RDONLY | O_BINARY, 0))  
     739                != -1); 
    699740        ::close(f); 
    700741         
     
    713754        write3b.Commit(); 
    714755        // Test it 
    715         testReadingFileContents(0, "test1", data+3, sizeof(data) - 3, false /*TestRAIDProperties*/); 
     756        testReadingFileContents(0, "test1", data+3, sizeof(data) - 3, false  
     757                /* TestRAIDProperties */); 
    716758 
    717759        // And once again, but this time making it a raid file 
     
    722764        write3c.Commit(true);   // make RAID 
    723765        // Test it 
    724         testReadingFileContents(0, "test1", data+7, sizeof(data) - 7, false /*TestRAIDProperties*/); 
     766        testReadingFileContents(0, "test1", data+7, sizeof(data) - 7, false  
     767                /*TestRAIDProperties*/); 
    725768 
    726769        // Test opening a file which doesn't exist 
     
    737780 
    738781                // Try removing the parity file 
    739                 TEST_THAT(::rename("testfiles/0_0/damage.rf", "testfiles/0_0/damage.rf-NT") == 0); 
     782                TEST_THAT(::rename("testfiles" DIRECTORY_SEPARATOR "0_0" 
     783                        DIRECTORY_SEPARATOR "damage.rf",  
     784                        "testfiles" DIRECTORY_SEPARATOR "0_0" 
     785                        DIRECTORY_SEPARATOR "damage.rf-NT") == 0); 
    740786                { 
    741787                        std::auto_ptr<RaidFileRead> pr0 = RaidFileRead::Open(0, "damage"); 
    742788                        pr0->Read(buffer, sizeof(data)); 
    743789                }                
    744                 TEST_THAT(::rename("testfiles/0_0/damage.rf-NT", "testfiles/0_0/damage.rf") == 0); 
    745                  
     790                TEST_THAT(::rename("testfiles" DIRECTORY_SEPARATOR "0_0" DIRECTORY_SEPARATOR "damage.rf-NT", "testfiles" DIRECTORY_SEPARATOR "0_0" DIRECTORY_SEPARATOR "damage.rf") == 0); 
     791         
    746792                // Delete one of the files 
    747                 TEST_THAT(::unlink("testfiles/0_1/damage.rf") == 0);    // stripe 1 
     793                TEST_THAT(::unlink("testfiles" DIRECTORY_SEPARATOR "0_1" DIRECTORY_SEPARATOR "damage.rf") == 0); // stripe 1 
    748794                 
    749795#ifdef TRF_CAN_INTERCEPT 
    750796                // Open it and read... 
    751797                { 
    752                         intercept_setup_error("testfiles/0_2/damage.rf", 0, EIO, SYS_read);     // stripe 2 
     798                        intercept_setup_error("testfiles" DIRECTORY_SEPARATOR "0_2" DIRECTORY_SEPARATOR "damage.rf", 0, EIO, SYS_read); // stripe 2 
    753799                        std::auto_ptr<RaidFileRead> pr1 = RaidFileRead::Open(0, "damage"); 
    754800                        TEST_CHECK_THROWS( 
     
    762808 
    763809                // Delete another 
    764                 TEST_THAT(::unlink("testfiles/0_0/damage.rf") == 0);            // parity 
     810                TEST_THAT(::unlink("testfiles" DIRECTORY_SEPARATOR "0_0" DIRECTORY_SEPARATOR "damage.rf") == 0); // parity 
    765811                 
    766812                TEST_CHECK_THROWS( 
     
    773819                RaidFileWrite::CreateDirectory(0, "dirread"); 
    774820                // Make some contents 
    775                 RaidFileWrite::CreateDirectory(0, "dirread/dfsdf1"); 
    776                 RaidFileWrite::CreateDirectory(0, "dirread/ponwq2"); 
    777                 { 
    778                         RaidFileWrite w(0, "dirread/sdf9873241"); 
     821                RaidFileWrite::CreateDirectory(0, "dirread" DIRECTORY_SEPARATOR "dfsdf1"); 
     822                RaidFileWrite::CreateDirectory(0, "dirread" DIRECTORY_SEPARATOR "ponwq2"); 
     823                { 
     824                        RaidFileWrite w(0, "dirread" DIRECTORY_SEPARATOR "sdf9873241"); 
    779825                        w.Open(); 
    780826                        w.Write(data, sizeof(data)); 
     
    782828                } 
    783829                { 
    784                         RaidFileWrite w(0, "dirread/fsdcxjni3242"); 
     830                        RaidFileWrite w(0, "dirread" DIRECTORY_SEPARATOR "fsdcxjni3242"); 
    785831                        w.Open(); 
    786832                        w.Write(data, sizeof(data)); 
     
    788834                } 
    789835                { 
    790                         RaidFileWrite w(0, "dirread/cskjnds3"); 
     836                        RaidFileWrite w(0, "dirread" DIRECTORY_SEPARATOR "cskjnds3"); 
    791837                        w.Open(); 
    792838                        w.Write(data, sizeof(data)); 
     
    804850                TEST_THAT(list_matches(names, dir_list1)); 
    805851                // Delete things 
    806                 TEST_THAT(::unlink("testfiles/0_0/dirread/sdf9873241.rf") == 0); 
     852                TEST_THAT(::unlink("testfiles" DIRECTORY_SEPARATOR "0_0" DIRECTORY_SEPARATOR "dirread" DIRECTORY_SEPARATOR "sdf9873241.rf") == 0); 
    807853                TEST_THAT(true == RaidFileRead::ReadDirectoryContents(0, std::string("dirread"), RaidFileRead::DirReadType_FilesOnly, names)); 
    808854                TEST_THAT(list_matches(names, file_list1)); 
    809855                // Delete something else so that it's not recoverable 
    810                 TEST_THAT(::unlink("testfiles/0_1/dirread/sdf9873241.rf") == 0); 
     856                TEST_THAT(::unlink("testfiles" DIRECTORY_SEPARATOR "0_1" DIRECTORY_SEPARATOR "dirread" DIRECTORY_SEPARATOR "sdf9873241.rf") == 0); 
    811857                TEST_THAT(false == RaidFileRead::ReadDirectoryContents(0, std::string("dirread"), RaidFileRead::DirReadType_FilesOnly, names)); 
    812858                TEST_THAT(list_matches(names, file_list1)); 
    813859                // And finally... 
    814                 TEST_THAT(::unlink("testfiles/0_2/dirread/sdf9873241.rf") == 0); 
     860                TEST_THAT(::unlink("testfiles" DIRECTORY_SEPARATOR "0_2" DIRECTORY_SEPARATOR "dirread" DIRECTORY_SEPARATOR "sdf9873241.rf") == 0); 
    815861                TEST_THAT(true == RaidFileRead::ReadDirectoryContents(0, std::string("dirread"), RaidFileRead::DirReadType_FilesOnly, names)); 
    816862                TEST_THAT(list_matches(names, file_list2)); 
  • box/chris/merge/test/win32/testlibwin32.cpp

    r456 r710  
    66 
    77#ifdef WIN32 
     8 
     9#include <assert.h> 
     10#include <AccCtrl.h> 
     11#include <Aclapi.h> 
    812 
    913#include "../../bin/bbackupd/BackupDaemon.h" 
     
    1317int main(int argc, char* argv[]) 
    1418{ 
     19        // ACL tests 
     20        char* exename = getenv("WINDIR"); 
     21 
     22        PSID psidOwner; 
     23        PSID psidGroup; 
     24        PACL pDacl; 
     25        PSECURITY_DESCRIPTOR pSecurityDesc; 
     26 
     27        DWORD result = GetNamedSecurityInfo( 
     28                exename, // pObjectName 
     29                SE_FILE_OBJECT, // ObjectType 
     30                DACL_SECURITY_INFORMATION | // SecurityInfo 
     31                GROUP_SECURITY_INFORMATION | 
     32                OWNER_SECURITY_INFORMATION, 
     33                &psidOwner, // ppsidOwner, 
     34                &psidGroup, // ppsidGroup, 
     35                &pDacl,     // ppDacl, 
     36                NULL,       // ppSacl, 
     37                &pSecurityDesc // ppSecurityDescriptor 
     38        ); 
     39        if (result != ERROR_SUCCESS) 
     40        { 
     41                printf("Error getting security info for '%s': error %d", 
     42                        exename, result); 
     43        } 
     44        assert(result == ERROR_SUCCESS); 
     45 
     46        char namebuf[1024]; 
     47        char domainbuf[1024]; 
     48        SID_NAME_USE nametype; 
     49        DWORD namelen = sizeof(namebuf); 
     50        DWORD domainlen = sizeof(domainbuf); 
     51 
     52        assert(LookupAccountSid(NULL, psidOwner, namebuf, &namelen, 
     53                domainbuf, &domainlen, &nametype)); 
     54 
     55        printf("Owner:\n"); 
     56        printf("User name:   %s\n", namebuf); 
     57        printf("Domain name: %s\n", domainbuf); 
     58        printf("Name type:   %d\n", nametype); 
     59        printf("\n"); 
     60 
     61        namelen = sizeof(namebuf); 
     62        domainlen = sizeof(domainbuf); 
     63 
     64        assert(LookupAccountSid(NULL, psidGroup, namebuf, &namelen, 
     65                domainbuf, &domainlen, &nametype)); 
     66 
     67        printf("Group:\n"); 
     68        printf("User name:   %s\n", namebuf); 
     69        printf("Domain name: %s\n", domainbuf); 
     70        printf("Name type:   %d\n", nametype); 
     71        printf("\n"); 
     72 
     73        ULONG numEntries; 
     74        PEXPLICIT_ACCESS pEntries; 
     75        result = GetExplicitEntriesFromAcl 
     76        ( 
     77                pDacl,       // pAcl 
     78                &numEntries, // pcCountOfExplicitEntries, 
     79                &pEntries    // pListOfExplicitEntries 
     80        ); 
     81        assert(result == ERROR_SUCCESS); 
     82 
     83        printf("Found %lu explicit DACL entries for '%s'\n\n", 
     84                (unsigned long)numEntries, exename); 
     85 
     86        for (ULONG i = 0; i < numEntries; i++) 
     87        { 
     88                EXPLICIT_ACCESS* pEntry = &(pEntries[i]); 
     89                printf("DACL entry %lu:\n", (unsigned long)i); 
     90 
     91                DWORD perms = pEntry->grfAccessPermissions; 
     92                printf("  Access permissions: ", perms); 
     93 
     94                #define PRINT_PERM(name) \ 
     95                if (perms & name) \ 
     96                { \ 
     97                        printf(#name " "); \ 
     98                        perms &= ~name; \ 
     99                } 
     100 
     101                PRINT_PERM(FILE_ADD_FILE); 
     102                PRINT_PERM(FILE_ADD_SUBDIRECTORY); 
     103                PRINT_PERM(FILE_ALL_ACCESS); 
     104                PRINT_PERM(FILE_APPEND_DATA); 
     105                PRINT_PERM(FILE_CREATE_PIPE_INSTANCE); 
     106                PRINT_PERM(FILE_DELETE_CHILD); 
     107                PRINT_PERM(FILE_EXECUTE); 
     108                PRINT_PERM(FILE_LIST_DIRECTORY); 
     109                PRINT_PERM(FILE_READ_ATTRIBUTES); 
     110                PRINT_PERM(FILE_READ_DATA); 
     111                PRINT_PERM(FILE_READ_EA); 
     112                PRINT_PERM(FILE_TRAVERSE); 
     113                PRINT_PERM(FILE_WRITE_ATTRIBUTES); 
     114                PRINT_PERM(FILE_WRITE_DATA); 
     115                PRINT_PERM(FILE_WRITE_EA); 
     116                PRINT_PERM(STANDARD_RIGHTS_READ); 
     117                PRINT_PERM(STANDARD_RIGHTS_WRITE); 
     118                PRINT_PERM(SYNCHRONIZE); 
     119                PRINT_PERM(DELETE); 
     120                PRINT_PERM(READ_CONTROL); 
     121                PRINT_PERM(WRITE_DAC); 
     122                PRINT_PERM(WRITE_OWNER); 
     123                PRINT_PERM(MAXIMUM_ALLOWED); 
     124                PRINT_PERM(GENERIC_ALL); 
     125                PRINT_PERM(GENERIC_EXECUTE); 
     126                PRINT_PERM(GENERIC_WRITE); 
     127                PRINT_PERM(GENERIC_READ); 
     128                printf("\n"); 
     129 
     130                if (perms) 
     131                { 
     132                        printf("  Bits left over: %08x\n", perms); 
     133                } 
     134                assert(!perms); 
     135 
     136                printf("  Access mode: "); 
     137                switch(pEntry->grfAccessMode) 
     138                { 
     139                case NOT_USED_ACCESS: 
     140                        printf("NOT_USED_ACCESS\n"); break; 
     141                case GRANT_ACCESS: 
     142                        printf("GRANT_ACCESS\n"); break; 
     143                case DENY_ACCESS: 
     144                        printf("DENY_ACCESS\n"); break; 
     145                case REVOKE_ACCESS: 
     146                        printf("REVOKE_ACCESS\n"); break; 
     147                case SET_AUDIT_SUCCESS: 
     148                        printf("SET_AUDIT_SUCCESS\n"); break; 
     149                case SET_AUDIT_FAILURE: 
     150                        printf("SET_AUDIT_FAILURE\n"); break; 
     151                default: 
     152                        printf("Unknown (%08x)\n", pEntry->grfAccessMode); 
     153                } 
     154 
     155                printf("  Trustee: "); 
     156                assert(pEntry->Trustee.pMultipleTrustee == NULL); 
     157                assert(pEntry->Trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE); 
     158                switch(pEntry->Trustee.TrusteeForm) 
     159                { 
     160                case TRUSTEE_IS_SID: 
     161                        { 
     162                                PSID trusteeSid = (PSID)(pEntry->Trustee.ptstrName); 
     163 
     164                                namelen = sizeof(namebuf); 
     165                                domainlen = sizeof(domainbuf); 
     166 
     167                                assert(LookupAccountSid(NULL, trusteeSid, namebuf, &namelen, 
     168                                        domainbuf, &domainlen, &nametype)); 
     169 
     170                                printf("SID of %s\\%s (%d)\n", domainbuf, namebuf, nametype); 
     171                        } 
     172                        break; 
     173                case TRUSTEE_IS_NAME: 
     174                        printf("Name\n"); break; 
     175                case TRUSTEE_BAD_FORM: 
     176                        printf("Bad form\n"); assert(0); 
     177                case TRUSTEE_IS_OBJECTS_AND_SID: 
     178                        printf("Objects and SID\n"); break; 
     179                case TRUSTEE_IS_OBJECTS_AND_NAME: 
     180                        printf("Objects and name\n"); break; 
     181                default: 
     182                        printf("Unknown form\n"); assert(0); 
     183                } 
     184 
     185                printf("  Trustee type: "); 
     186                switch(pEntry->Trustee.TrusteeType) 
     187                { 
     188                case TRUSTEE_IS_UNKNOWN: 
     189                        printf("Unknown type.\n"); break; 
     190                case TRUSTEE_IS_USER: 
     191                        printf("User\n"); break; 
     192                case TRUSTEE_IS_GROUP: 
     193                        printf("Group\n"); break; 
     194                case TRUSTEE_IS_DOMAIN: 
     195                        printf("Domain\n"); break; 
     196                case TRUSTEE_IS_ALIAS: 
     197                        printf("Alias\n"); break; 
     198                case TRUSTEE_IS_WELL_KNOWN_GROUP: 
     199                        printf("Well-known group\n"); break; 
     200                case TRUSTEE_IS_DELETED: 
     201                        printf("Deleted account\n"); break; 
     202                case TRUSTEE_IS_INVALID: 
     203                        printf("Invalid trustee type\n"); break; 
     204                case TRUSTEE_IS_COMPUTER: 
     205                        printf("Computer\n"); break; 
     206                default: 
     207                        printf("Unknown type %d\n", pEntry->Trustee.TrusteeType);  
     208                        assert(0); 
     209                } 
     210 
     211                printf("\n"); 
     212        } 
     213 
     214        assert(LocalFree((HLOCAL)pEntries) == 0); 
     215        assert(LocalFree((HLOCAL)pSecurityDesc) == 0); 
     216 
    15217        chdir("c:\\tmp"); 
    16218        openfile("test", O_CREAT, 0); 
     
    26228                { 
    27229                        info = readdir(ourDir); 
    28                         if ( info ) printf("File/Dir name is : %s\r\n", info->d_name); 
    29  
    30                 }while ( info != NULL ); 
     230                        if (info) printf("File/Dir name is : %s\r\n", info->d_name); 
     231                } 
     232                while (info != NULL); 
    31233 
    32234                closedir(ourDir); 
    33  
    34235        } 
    35236         
     
    42243                { 
    43244                        info = readdir(ourDir); 
    44                         if ( info == NULL ) break; 
     245                        if (info == NULL) break; 
    45246                        std::string file(diry + info->d_name); 
    46247                        stat(file.c_str(), &ourfs); 
    47                         if ( info ) printf("File/Dir name is : %s\r\n", info->d_name); 
    48  
    49                 }while ( info != NULL ); 
     248                        if (info) printf("File/Dir name is : %s\r\n", info->d_name); 
     249                } 
     250                while ( info != NULL ); 
    50251 
    51252                closedir(ourDir); 
     
    55256        stat("c:\\windows", &ourfs); 
    56257        stat("c:\\autoexec.bat", &ourfs); 
    57         printf("Finished dir read"); 
    58 #if 0 
    59         //remove - sleepycat include a version of getopt - mine never REALLY worked ! 
     258        printf("Finished dir read\n"); 
     259 
    60260        //test our getopt function 
    61         std::string commline("-q -c fgfgfg -f -l hello"); 
    62  
    63         int c; 
    64         while((c = getopt(commline.size(), (char * const *)commline.c_str(), "qwc:l:")) != -1) 
    65         { 
    66                 printf("switch = %c, param is %s\r\n", c, optarg); 
    67         } 
    68 #endif 
     261        char * test_argv[] =  
     262        { 
     263                "foobar.exe", 
     264                "-qwc", 
     265                "-", 
     266                "-c", 
     267                "fgfgfg", 
     268                "-f", 
     269                "-l", 
     270                "hello", 
     271                "-", 
     272                "force-sync", 
     273                NULL 
     274        }; 
     275        int test_argc; 
     276        for (test_argc = 0; test_argv[test_argc]; test_argc++) { } 
     277        const char* opts = "qwc:l:"; 
     278 
     279        assert(getopt(test_argc, test_argv, opts) == 'q'); 
     280        assert(getopt(test_argc, test_argv, opts) == 'w'); 
     281        assert(getopt(test_argc, test_argv, opts) == 'c'); 
     282        assert(strcmp(optarg, "-") == 0); 
     283        assert(getopt(test_argc, test_argv, opts) == 'c'); 
     284        assert(strcmp(optarg, "fgfgfg") == 0); 
     285        assert(getopt(test_argc, test_argv, opts) == '?'); 
     286        assert(optopt == 'f'); 
     287        assert(getopt(test_argc, test_argv, opts) == 'l'); 
     288        assert(strcmp(optarg, "hello") == 0); 
     289        assert(getopt(test_argc, test_argv, opts) == -1); 
     290        // assert(optopt == 0); // no more options 
     291        assert(strcmp(test_argv[optind], "-") == 0); 
     292        assert(strcmp(test_argv[optind+1], "force-sync") == 0); 
    69293        //end of getopt test 
    70294         
    71295        //now test our statfs funct 
    72296        stat("c:\\cert.cer", &ourfs); 
    73          
    74          
    75297 
    76298        char *timee; 
     
    78300        timee = ctime(&ourfs.st_mtime); 
    79301 
    80         if ( S_ISREG(ourfs.st_mode)) 
    81         { 
    82                 printf("is a normal file"); 
     302        if (S_ISREG(ourfs.st_mode)) 
     303        { 
     304                printf("is a normal file\n"); 
    83305        } 
    84306        else 
    85307        { 
    86                 printf("is a directory?"); 
    87         } 
    88  
    89         lstat("c:\\windows", &ourfs); 
     308                printf("is a directory?\n"); 
     309                exit(1); 
     310        } 
     311 
     312        lstat(getenv("WINDIR"), &ourfs); 
    90313 
    91314        if ( S_ISDIR(ourfs.st_mode)) 
    92315        { 
    93                 printf("is a directory"); 
     316                printf("is a directory\n"); 
    94317        } 
    95318        else 
    96319        { 
    97                 printf("is a file?"); 
     320                printf("is a file?\n"); 
     321                exit(1); 
    98322        } 
    99323 
     
    106330        closelog(); 
    107331 
     332        /* 
    108333        //first off get the path name for the default  
    109334        char buf[MAX_PATH]; 
     
    113338        std::string conf("-c " + buffer.substr(0,(buffer.find("win32test.exe"))) + "bbackupd.conf"); 
    114339        //std::string conf( "-c " + buffer.substr(0,(buffer.find("bbackupd.exe"))) + "bbackupd.conf"); 
    115  
     340        */ 
    116341 
    117342        return 0; 
  • box/chris/merge/win32.bat

    r456 r710  
    33echo quick and dirty to get up and running by generating the required files  
    44echo using Cygwin and Perl 
     5 
     6copy .\infrastructure\BoxPlatform.pm.in .\infrastructure\BoxPlatform.pm 
    57 
    68cd .\bin\bbackupquery\ & perl ./../../bin/bbackupquery/makedocumentation.pl 
     
    2628cd ..\..\ 
    2729 
    28 copy lib\win32\config.h.win32 lib\common\BoxConfig.h 
     30perl -i.orig -pe 's/@PERL@/perl/' ./test/bbackupd/testfiles/bbackupd.conf 
Note: See TracChangeset for help on using the changeset viewer.